编程小白打卡百度字节面试题C语言(反转链表II)

反转链表II

struct ListNode*reverse(struct ListNode** head2)//反转部分链表(头插法)
{
    if(*head2==NULL)
    {
        return NULL;
    }
    struct ListNode*p=NULL;
    struct ListNode*p1=*head2;
    struct ListNode*p2=(*head2)->next;
    while(p1)
    {
        p1->next=p;
        p=p1;
        p1=p2;
        if(p2)
        {
            p2=p2->next;
        }
    }
    return p;
} 
struct ListNode* reverseBetween(struct ListNode* head, int left, int right){
    if(head==NULL)
    {
        return NULL;
    }
    if(head->next==NULL)
    return head;
    int i=0;
    struct ListNode*tail=head;
    struct ListNode*copy_tail=tail;
    struct ListNode*copy_tail2=tail;
    for(i=1;i<right;i++)
    {
        tail=tail->next;
    }
    copy_tail=tail->next;
    tail->next=NULL;
    struct ListNode*newhead=(struct ListNode*)malloc(sizeof(struct ListNode));
    newhead->next=head;
    for(i=0;i<left;i++)
    {
        copy_tail2=newhead;
        newhead=newhead->next;
    }
    struct ListNode*p2=reverse(&newhead);
    copy_tail2->next=p2;
    newhead->next=copy_tail;
    if(left==1)//考虑特殊情况(这里也需要多次画图)
    return p2;
    return head;
}

在这里插入图片描述

目前没学C++,数据结构也是略知一二,当作是一次做题记录吧。

复制带随机指针的链表

struct Node* copyRandomList(struct Node* head)
{
    if (head == NULL)
        return NULL;
    struct Node* tail = head;
    while (tail)
    {
        struct Node* copy = (struct Node*)malloc(sizeof(struct Node));
        copy->next = tail->next;
        tail->next = copy;
        copy->val=tail->val;
        tail = tail->next->next;
    }
    tail=head->next;
    struct Node*prev_tail=head;
    while(tail)
    {
        tail->random = prev_tail->random==NULL?NULL:prev_tail->random->next;
        tail=tail->next==NULL?NULL:tail->next->next;
        prev_tail=prev_tail->next->next;
    }
    struct Node* tail2 = head;
    struct Node* copy_list =(struct Node*)malloc(sizeof(struct Node));
    struct Node* res=copy_list;
    //copy_list->next=NULL;
    while(tail2)//&&copy_list)
    {
        tail2=tail2->next;
        copy_list->next=tail2;
        tail2=tail2->next;
        copy_list=copy_list->next;//这个地方要注意!!!
    }
    copy_list= NULL;
    return res->next;
}

中间有个地方卡了好久。。。最后得出写代码不能老想着偷懒,哈哈哈

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

爱写代码的刚子

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值