0
点赞
收藏
分享

微信扫一扫

【leetcode题解】——链表OJ题

天行五煞 2022-04-03 阅读 35

文章目录


前言

学习数据结构ing……
在这里插入图片描述


`

一、21. 合并两个有序链表

struct ListNode* mergeTwoLists(struct ListNode* l1, struct ListNode* l2){
    if(l1==NULL)
    {
        return l2;
    }
    if(l2==NULL)
    {
        return l1;
    }
    struct ListNode* head=NULL;
    struct ListNode* tail=NULL;
    if(l1->val>l2->val)
    {
        head=tail=l2;
        l2=l2->next;
     
        // l1=l1->next;
    }
    else
    {
        head=tail=l1;
        l1=l1->next;
  
        //l2=l2->next;
    }
    while(l1!=NULL&&l2!=NULL)
    {
        if(l1->val>l2->val)
        {
            tail->next=l2;
            l2=l2->next;
        }
        else
        {
            tail->next=l1;
            l1=l1->next;
        }
        tail=tail->next;
    }
    if(l1)
    {
         tail->next=l1;
    }
    if(l2)
    {
        tail->next=l2;
    }
    return head;
}

二、876. 链表的中间结点

struct ListNode* middleNode(struct ListNode* head){
struct ListNode* slow=head;
struct ListNode* fast=head;
while(fast&&fast->next)
{
    slow=slow->next;
    fast=fast->next->next;

}
return slow;
}

三、206. 反转链表

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

}
return n1;
}
struct ListNode* reverseList(struct ListNode* head){
struct ListNode* newnode=NULL;
struct ListNode* cur=head;
while(cur)
{
    struct ListNode* next=cur->next;
    cur->next=newnode;
    newnode=cur;
    cur=next;
}
return newnode;
}

四、 141. 环形链表

题解:

bool hasCycle(struct ListNode *head) {
    struct ListNode *solve=head;
    struct ListNode *fast=head;
    while(fast&&fast->next)
    {
        fast=fast->next->next;
        solve=solve->next;
        if(fast==solve)
        {
            return true;
        }
    }
    return false;
}

五、142. 环形链表 II

    struct ListNode *detectCycle(struct ListNode *head) {
    struct ListNode *slow=head;
    struct ListNode *fast=head;
    while(fast&&fast->next)
    {
        fast=fast->next->next;
        slow=slow->next;
        if(fast==slow)
        {
            struct ListNode *meet=fast;
            struct ListNode *begin=head;
            while(begin!=meet)
            {
               meet=meet->next;
               begin=begin->next;
            }
            return meet;
           
        }
    }
    return NULL;
}
举报

相关推荐

0 条评论