理解链表操作之归并+删除奇数节点+逆序建立

以下是归并两个有序列表的算法
思路:
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;

}
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值