以下是归并两个有序列表的算法
思路:
1.创建一个新的头结点,并分配内存空间
2.创建一个tt结构体指针指向头结点,由他来完成后续的连接操作,不要去动头结点,我们最后要返回他的,所以他的地址不能去改
3.创建临时指针,保存每一步操作的结果
4.用tt指针连接temp同时将tt移动到temp表示当前的指针位置
5.最后连接剩下的没有归并完的链表
6.返回第一个节点(也可以返回头节点,看需求)
struct stud_node *InserDoc(struct stud_node *list1,struct stud_node *list2){
struct stud_node *list=(struct stud_node *)malloc(sizeof(struct stud_node));
struct stud_node *tt=list;
struct stud_node *temp;
while(list1&&list2){
temp=(struct stud_node *)malloc(sizeof(struct stud_node));
if(list1->num<list2->num){
temp->num=list1->num;
temp->next=NULL;
tt->next=temp;
tt=tt->next;
list1=list1->next;
}
else{
temp->num=list2->num;
temp->next=NULL;
tt->next=temp;
tt=tt->next;
list2=list2->next;
}
}
if(list1){
tt->next=list1;
}
if(list2){
tt->next=list2;
}
return list->next;
}
1.原节点传进来是没有头结点的
2.创建一个新的头结点
3.用tt指向新的头结点准备后续操作
4.创建临时节点
5.对于那些奇数的就连接在一起,同时tt移动到当前指针
6.最后返回第一个节点(同上,看需求)
struct stud_node *DeleteDoc(struct stud_node *head){
struct stud_node *lhead=(struct stud_node *)malloc(sizeof(struct stud_node));
struct stud_node *tt;
tt=lhead;
struct stud_node *temp;
while(head){
temp=(struct stud_node *)malloc(sizeof(struct stud_node));
if(head->num%2!=0){
temp->num=head->num;
temp->next=NULL;
tt->next=temp;
tt=tt->next;
}
head=head->next;
}
return lhead->next;
}
总结:个人还是习惯于头结点,搞清楚临时节点的作用,脑海中想象一下谁和谁连接,谁断开了,谁的下个是啥,现在的节点是啥,链表的操作就不难了
提问:逆序建立一个链表? -1结束
struct stud_node *Creat_Stu_Doc(){
struct stud_node *head=(struct stud_node *)malloc(sizeof(struct stud_node));
struct stud_node *temp;
head->next=NULL;
struct stud_node *L=head;
int n;
scanf("%d",&n);
while(n!=-1){
temp=(struct stud_node *)malloc(sizeof(struct stud_node));
//关键三步如下,脑海中画个图搞明白指向,L始终在头结点的位置(有注意到吗)
temp->num=n;
temp->next=L->next;
L->next=temp;
scanf("%d",&n);
}
return head->next;
}