标签:Node 03 head name 30 next pf 2021 ptr
#define _CRT_SECURE_NO_WARNINGS
#include<stdio.h>
#include<stdlib.h>
typedef struct Node_ {
char name;
struct Node_* next;
}Node;
typedef struct Tree_ {
char name;
struct Tree_* cl;
struct Tree_* cr;
}TreeNode;
void read_list(Node* head);
Node* init_list(Node* head);//无头链表
void read_list2(Node* head);
Node* init_list2(Node* head);
Node* delete(Node* head, char dname);
Node* delete2(Node* head, char dname);
int main()
{
Node* head=NULL;
head = init_list2(head);
read_list2(head);
delete2(head, 'm');
read_list2(head);
}
Node* init_list(Node*head)//初始化无头链表
{
char a;
scanf(" %c", &a);
Node* last = head;
while (a != 'q')
{
Node* ptr = (Node*)malloc(sizeof(Node));
if (ptr)
{
ptr->name = a;
ptr->next = NULL;
}
if (!head)
{
head = ptr;
last = ptr;
}
else {
if(last)last->next = ptr;
last = ptr;
}
scanf(" %c", &a);
}
return head;
}
void read_list(Node* head)//读无头链表
{
while (head)
{
printf("%c", head->name);
head = head->next;
}
}
Node* init_list2(Node* head)//初始化有头链表
{
char a;
head = (Node*)malloc(sizeof(Node));
Node* last = head;
head->next = NULL;
scanf(" %c", &a);
while (a != 'q')
{
Node* ptr = (Node*)malloc(sizeof(Node));
if(ptr)ptr->name = a;
if(ptr)ptr->next = NULL;
if(last)last->next = ptr;
last = ptr;
scanf(" %c", &a);
}
return head;
}
void read_list2(Node* head)//有头链表
{
head = head->next;
while (head)
{
printf("%c", head->name);
head = head->next;
}
}
Node* delete(Node* head, char dname)//无头
{
Node* p;
while(head->name == dname)//被删掉的在头部
{
p = head;
head = head->next;
free(p);
}
p = head->next;
Node* pf = head;
while(p&&p->next)//判断p是不是最后一个,不是的话
{
if (p->name == dname)
{
Node* tmp;
pf->next = p->next;
tmp = p;
p = p->next;//指向下一个
free(tmp);
}
else {
pf = p;
p = p->next;
}
}
if (p&&p->next == NULL && (p->name == dname))//要删除的在尾部
{
pf->next = NULL;
free(p);
}
return head;
}
Node* delete2(Node* head, char dname)//有头
{
Node* p;
p = head->next;
Node* pf = head;//pf为p的前一个指针
while (p&&p->next)//判断p是不是最后一个,不是的话
{
if (p->name == dname)
{
Node* tmp;
pf->next = p->next;//
tmp = p;
p = p->next;//指向下一个pf不变
free(tmp);
}
else {
pf = p;
p = p->next;
}
}
if (p&&p->next == NULL && (p->name == dname))//要删除的在尾部
{
pf->next = NULL;//前一个置为空,否则读取时指针将解引用野指针
free(p);
}
return head;
}
有头链表和无头链表的初始化,读取,删除元素
标签:Node,03,head,name,30,next,pf,2021,ptr 来源: https://blog.csdn.net/beyondzty/article/details/115322341
本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享; 2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关; 3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关; 4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除; 5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。