Leetcode 143. Reorder List(Medium)
Given a singly linked list L: L0→L1→…→Ln-1→Ln,
reorder it to: L0→Ln→L1→Ln-1→L2→Ln-2→…
You must do this in-place without altering the nodes' values.
For example,
Given {1,2,3,4}
, reorder it to {1,4,2,3}
.
搞了一天多,纠结到一个while 写成了if...........
思路很清晰, 找出链表的中点,翻转第二个链表,合并两个链表。
/** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode(int x) : val(x), next(NULL) {} * }; */ class Solution { public: ListNode* findMid(ListNode* head){ // 找出链表的中点,快慢指针解决,很经典。 /*if (head == NULL || head -> next == NULL){ return head; }*/ ListNode* slow = head; ListNode* fast = head; while (fast != NULL && fast -> next != NULL){ // 注意判断条件很容易出问题 slow = slow -> next; fast = fast -> next -> next; } return slow; } ListNode* reverseList(ListNode* head){ // 翻转一个链表 ListNode* newhead = NULL; while (head != NULL){ // 一开始写成了if 纠结了一天,长记性。。。 ListNode* nextp = head -> next; head -> next = newhead; newhead = head; // 统一后移 head = nextp; } return newhead; } ListNode* merge(ListNode* l1, ListNode* l2){ // 合并两个链表 if (l2 == NULL){ return l1; } ListNode* head = l1; while (l1 != NULL && l2 != NULL){ ListNode* nextp = l1 -> next; l1 -> next = l2; l2 = l2 -> next; l1 -> next -> next = nextp; l1 = nextp; // l1后移 } return head; } void reorderList(ListNode* head) { if (head == NULL || head -> next == NULL){ return; } ListNode* mid = findMid(head); // 1.找到链表的中点 ListNode* l1 = head; ListNode* l2 = mid -> next; mid -> next = NULL; // 2. 断开链表 l2 = reverseList(l2); // 3. 翻转l2 head = merge(l1, l2); // 4. 合并两个链表 } };