LeetCode24、两两交换链表中的节点、19、删除链表的倒数第N个节点、02.07、链表相交、142、环形链表II

LeetCode24、两两交换链表中的节点

struct ListNode* swapPairs(struct ListNode* head) {
    struct ListNode* dummyNode = (struct ListNode*)malloc(sizeof(struct ListNode));
    dummyNode->next = head;
    struct ListNode* curr = dummyNode;
    //如果链表节点为偶数个,则curr->next=NULL时结束循环
    //如果链表节点为奇数个,则curr->next->next时结束循环
    while(curr->next != NULL && curr->next->next!=NULL)
    {
        struct ListNode* temp = curr->next;
        struct ListNode* temp1 = curr->next->next->next;

        curr->next = curr->next->next;
        curr->next->next = temp;
        temp->next = temp1;
        curr = curr->next->next;
    }
    return dummyNode->next;
}

LeetCode19、删除链表的倒数第N个节点

struct ListNode* removeNthFromEnd(struct ListNode* head, int n) {
    struct ListNode dummy = {0,NULL};
    struct ListNode* dummyNode = &dummy;
    dummyNode->next = head;
    n = n + 1;
    struct ListNode* fast = dummyNode;
    struct ListNode* slow = dummyNode;
    while(n-- && fast!=NULL)
    {
        fast = fast->next;
    }
    while(fast!=NULL)
    {
        fast = fast->next;
        slow = slow->next;
    }
    slow->next = slow->next->next;
    return dummyNode->next;
}

LeetCode02.07、链表相交

struct ListNode* getIntersectionNode(struct ListNode* headA, struct ListNode* headB) {
    struct ListNode* s = NULL;
    struct ListNode* l = NULL;
    int a = 0; int b = 0; int gap = 0;
    s = headA;
    while (s)
    {
        a++;
        s = s->next;
    }
    s = headB;
    while (s)
    {
        b++;
        s = s->next;
    }
    if (a > b)
    {
        gap = a - b;
        s = headA;
        l = headB;
    }
    else {
        gap = b - a;
        s = headB;
        l = headA;
    }
    
    while (gap--)
    {
        s = s->next;
    }

    while (s)
    {
        if (l == s) return s;
        l = l->next;
        s = s->next;
    }
    return NULL;
}

LeetCode142、环形链表II

struct ListNode *detectCycle(struct ListNode *head) {
    struct ListNode *fast = head;
    struct ListNode *slow = head;
    while(fast!=NULL && fast->next!=NULL)
    {
        fast = fast->next->next;
        slow = slow->next;
        if(fast == slow)
        {
            struct ListNode *h = head,*f = fast;
            while(h != f)
            {
                h=h->next;
                f=f->next;
            }
            return h;
        }
    }
    return NULL;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值