链表插入
编程实现:输入一个正整数 n(0<n<=9)和一组(n个)升序的整数,建立单向链表,再输入一个整数 x,把 x 插入到这组数据中,使该组数据仍然有序。
输入样例:
5 (数据的个数n=5)
1 2 4 5 7 (5个有序整数)
3 (待插入整数x=3)
输出样例:
1 2 3 4 5 7
思路:
链表插入的关键在于找到位置,创建节点q,储存需要插入链表的x值,再创建两个指针分别为p, p1,赋初始值,并确保p1要指向p后面的节点,p1的功能是寻找值,p的功能是定位,一定是指在节点q插入的位置的前一个节点上,当找到位置,退出循环后,进行链表插入的操作。
主要代码展示:
原代码:
struct Node *addlist(struct Node *head,int x){
int index=0;//定位
struct Node *p1=head,*p2=head->next,*p=head;
while(p2){
index++;
if(x>p1->data&&x<p2->data) break;//这种写法在x<表头或x>表尾的数的情况下答案错误
p1=p1->next;
p2=p2->next;
}
for(int i=1;i<index;i++)
p=p->next;
struct Node *q=(struct Node*)malloc(sizeof(struct Node));
q->data=x;
q->next=p->next;
p->next=q;
return head;
}
修改1.0:
struct Node *addlist(struct Node *head,int x){
int index=0;//定位
struct Node *p2=head->next,*p=head;
while(p2){
if(x<p2->data) break;
index++;
p2=p2->next;
}
for(int i=0;i<index;i++)
p=p->next;
struct Node *q=(struct Node*)malloc(sizeof(struct Node));
q->data=x;
q->next=p->next;
p->next=q;
return head;
}
修改2.0:
struct Node *addlist(struct Node *head,int x){
struct Node *p1 = head->Next, *p = head;
while(p1){
if(p1->Data > X) break;
p = p->Next;
p1 = p1->Next;
}
List q = (struct Node*)malloc(sizeof(struct Node));
q->Data = X;
q->Next = p->Next;
p->Next = q;
return head;
ps:存在链表有另外插入数据的情况下,链表创建需带头节点,有利于在表头的数据插入;