Day18_ [LeetCode中等] 143. 重排链表

Day18: [LeetCode中等] 143. 重排链表

题源:

来自leetcode题库:

https://leetcode-cn.com/problems/reorder-list/

思路:

思路就是把原链表分为两个链表,然后反转第二个链表,然后把反转后的链表2间隔插入到链表1中。

代码:

dirty code凑合看吧

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution {
public:
    void reorderList(ListNode* head) {
        if(!head||head->next==NULL) return;
        auto p=head,q=head;
        //计算链表总长
        int Len=0;
        while(p){
            Len++;
            p=p->next;
        }
        p=head;
        //计算两个分链表的长度
        int Len1;
        if(Len%2==0) Len1=Len/2;
        else Len1=Len/2+1;
        int Len2=Len-Len1;
        //让p,q成为两个分链表的头指针
        for(int i=0;i<Len1-1;i++){
            p=p->next;
        }
        q=p->next;
        p->next=NULL;
        auto rear=q;
        while(rear->next!=NULL){
            rear=rear->next;
        }
        //反转q对应的分链表2
        auto qq=q->next;
        q->next=NULL;
        for(int i=0;i<Len2-1;i++){
            auto temp=qq;
            qq=qq->next;
            temp->next=q;
            q=temp;
        }
        //将链表2间隔插入到链表1中
        p=head;
        while(q){
            auto temp=q;
            q=q->next;
            temp->next=p->next;
            p->next=temp;
            p=p->next->next;
        }
        return;
    }
};
发布了49 篇原创文章 · 获赞 13 · 访问量 546

猜你喜欢

转载自blog.csdn.net/qq2215459786/article/details/103165965