otal Accepted: 54991 Total Submissions: 252600 Difficulty: 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}
.
/** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode(int x) : val(x), next(NULL) {} * }; */ class Solution { public: ListNode* reverseList(ListNode* head) { ListNode* cur = head; ListNode* newHead = NULL; ListNode* next = NULL; while(cur){ next = cur->next; cur->next = newHead; newHead = cur; cur = next; } return newHead; } void reorderList(ListNode* head) { if(head==NULL || head->next==NULL){ return; } ListNode* slow = head; ListNode* fast = head; ListNode* pre = NULL; while(fast){ pre = slow; slow = slow->next; fast->next ? fast = fast->next->next : fast = NULL; } pre->next = NULL; ListNode* head2 = reverseList(slow); ListNode* cur = head; ListNode* cur_next = NULL; ListNode* cur2 = head2; ListNode* cur2_next = NULL; while(cur2){ cur_next = cur->next; cur2_next = cur2->next; cur->next = cur2; cur2->next = cur_next; cur = cur_next; cur2 = cur2_next; } } };
Next challenges: (M) Partition List (M) Convert Sorted List to Binary Search Tree (H) Copy List with Random Pointer
时间: 2024-10-20 01:43:57