143. Reorder List

来源:互联网 发布:淘宝开网店书籍有用吗 编辑:程序博客网 时间:2024/04/27 20:07

这道题按要求把链表重新排序。

我的思路是对的,就是首先快慢指针,把链表后半部分倒序,然后再和左半部分连。但是中间指针的处理实在繁琐。

/** * 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 || !head->next->next)   return;        ListNode *fast = head;        ListNode *slow = head;        while(fast && fast->next && fast->next->next){            slow = slow->next;            fast = fast->next->next;        }        ListNode *mid = slow->next;        slow->next = NULL;        ListNode *cur = mid, *pre = NULL;        while(cur){            ListNode *curnext = cur->next;            cur->next = pre;            pre = cur;            cur = curnext;        }        while(head && pre){            ListNode* headnext = head->next;            head->next = pre;            pre = pre->next;            head->next->next = headnext;            head = headnext;        }    }};


原创粉丝点击