首先是链表的创建,以及初始化链表
struct Node * Creat_Single_Linked() //创建一个单链表,相当于链表初始化
{
struct Node *head=NULL; //头指针
struct Node *tail=NULL; //尾指针
Elemtype data;
while(1) //这个循环是为了控制一直能够添加节点,当你scanf输入0时添加结束
{
scanf("%d",&data);
if(data==0) //当输入0时添加节点结束,返回一个链表的头指针
{
return head;
}
else
{
if(head==NULL) //从无到有,头节点为空,所以将头节点指向第一个节点
{
struct Node *pnew=malloc(sizeof(struct Node));
pnew->val=data;
pnew->next=NULL;
head=pnew;
tail=pnew; //将尾节点指向新添加的节点,但这里是第一个节点所以它既是头也是尾
}
else //从少到多
{
struct Node *pnew=malloc(sizeof(struct Node));
pnew->val=data;
pnew->next=NULL;
tail->next=pnew;
tail=pnew;
}
}
}
}
链表节点的增加
struct Node * Add_List_Node(struct Node * head,Elemtype value,Elemtype seat)
{ //head表示头节点,value表示添加节点的值,seat添加节点的位置
if(head==NULL)
{
printf("该链表为空,不能添加");
return 0;
}
struct Node * H=head;
int record=0;
while(H) //遍历直到最后一个节点
{
record++;
if(record==seat-1)
{
if(H->next==NULL) //判断H是不是为尾节点,如果是尾节点就用尾插法
{
struct Node *p=malloc(sizeof(struct Node)); // 为新的节点分配内存空间
p->val=value;
p->next=NULL;
H->next=p;
return head;
}
else // 如果不是尾节,那就是插入两节点之间
{
struct Node *p=malloc(sizeof(struct Node)); // 为新的节点分配内存空间
p->val=value;
p->next=H->next->next;
H->next=p;
return head;
}
}
H=H->next;
}
修改单链表某一节点值
void Node * Modify_List_Node(struct Node * head,Elemtype value,Elemtype seat)
{ //head表示头节点,value表示添加节点的值,seat添加节点的位置
if(head==NULL) //如果链表为空也就没有修改的必要了
{
printf("该链表为空链表\n");
return 0;
}
else
{
struct Node * h=head; //初学者,可能很多人会犯这个错,不能直接用头指针直接去循环,否则头指针发生改变之前的节点就可能找不到了,所以记住头指针一定要动!!!
int record=0; //标记你要修改点的位置
while(h)
{
record++;
if(record==seat)
{
h->val=value;
break;
}
h=h->next;
}
}
}
找查链表是否有该节点
struct Node * Select_List_Node(struct Node * head,Elemtype value)
{
if(head==NULL)
{
printf("链表为空\n");
return 0;
}
else
{
struct Node *s=head;
while(s)
{
if(s->val==value)
{
printf("找到了\n");
break;
}
}
}
return s;
输出整个链表
void traverse_single_linked(struct Node * linked) //打印链表
{
if(linked==NULL)
{
printf("链表为空\n");
return 0;
}
struct Node *s=linked;
while(s)
{
printf("%d\t",s->val);
s=s->next;
}
putchar('\n');
}
数据结构的定义
typedef int Elemtype;
struct Node //单链表节点
{
Elemtype val;
struct Node* next;
};
直到写到这我才发现链表的删除函数没有写,但由于时间关系也就没有加上了,想要的同学可以私信我。