1.在链表中间插入数据
如果按照结点数据排序结果应在链表中间插入新结点,则将
待插入结点p的指针域指向下一结点,而前一结点的指针域指向
待插入的结点。
p->next = pr->next;
pr->next = p;
2.在链表的尾部插入数据
如果在链表的末尾插入新结点,则将链表的最后一个结点的指针指向待插入结点p,而待插入结点p的指针域赋值为NULL。
#include <malloc.h>
#include <stdio.h>
struct Link
{
int data;
struct Link *next;
};
struct Link *InsertLast(struct Link *head, int x){
struct Link *p, *pr;
p = (struct Link *) malloc(sizeof(struct Link));// 建立节点p,动态的分配内存
if(p==NULL)
printf("error");
p->data = x;
// 查找表尾(插入位置)pr
pr= head;
while(pr!=NULL && pr->next!=NULL)
pr = pr->next;
// 插入数据
if(pr==NULL) { // 在空表中插入
p->next = pr;
head = p;
} else { // 在pr之后插入p
p->next = pr->next;
pr->next = p;
}
return head;// 返回新表头
}
//输出链表
void PrintList(struct Link *head)
{
struct Link *p;
int i=1;
p=head;
while(p!=NULL)
{
printf("%d%5d",i,p->data);
printf("\n");
p=p->next;
i++;
}
}
void main()
{
struct Link a={30},b={40},c={50};
struct Link *head;
a.next=&b;
b.next=&c;
c.next=NULL;
head=&a;
head=InsertLast(head,1225);
PrintList(head);
}