实战Leetcode(四)

Practice makes perfect!

在这里插入图片描述

实战一:
在这里插入图片描述
在这里插入图片描述

这个题由于我们不知道两个链表的长度我们也不知道它是否有相交的节点,所以我们的方法是先求出两个链表的长度,长度长的先走相差的步数,使得两个链表处于同一起点,两个链表在同时走,如果两个链表节点的地址相等就存在相交的节点,在放回第一个节点就可以了。

struct ListNode *getIntersectionNode(struct ListNode *headA, struct ListNode *headB) {
    struct ListNode* curA=headA;
    struct ListNode* curB=headB;
    int lenA=1;
    int lenB=1;
    while(curA->next)
    {
        lenA++;
        curA=curA->next;
    }
    while(curB->next)
    {
        lenB++;
        curB=curB->next;
    }
    struct ListNode* longlist=headA;
    struct ListNode* shortlist=headB;
    int k=abs(lenA-lenB);
    if(lenA<lenB)
    {
        longlist=headB;
        shortlist=headA;
    }
    while(k--)
    {
        longlist=longlist->next;
    }
    while(longlist!=shortlist)
    {
        longlist=longlist->next;
        shortlist=shortlist->next;
    }
    return shortlist;
    
}

注意:代码中的abs是求绝对值的函数。

实战二:
在这里插入图片描述
在这里插入图片描述

我们用三个指针,n1为空,n2指向头结点,n3指向头结点的下一个节点,当我们遍历的时候,我们头结点的下一个节点指向n1,n1挪n2的位置,n2挪到n3的位置,遍历完成的时候n2和n3都为空指针,而我们的n1则表示头结点,现在的头结点却是原链表的尾节点。

struct ListNode* reverseList(struct ListNode* head) {
    if(head==NULL)
    {
        return NULL;
    }
    struct ListNode* n1,*n2,*n3;
    n1=NULL;
    n2=head;
    n3=head->next;
    while(n2)
    {
        n2->next=n1;
        n1=n2;
        n2=n3;
        if(n3)
        {
            n3=n3->next;
        }
    }
    return n1;
}

方法来源于积累,继续努力!

  • 41
    点赞
  • 35
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 69
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

Lehjy

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

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

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

打赏作者

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

抵扣说明:

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

余额充值