forked from wisdompeak/LeetCode
-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
1. Use fast and slow pointers; 2. More elegant revert and insertion.
- Loading branch information
Showing
1 changed file
with
39 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,39 @@ | ||
/** | ||
* Definition for singly-linked list. | ||
* struct ListNode { | ||
* int val; | ||
* ListNode *next; | ||
* ListNode() : val(0), next(nullptr) {} | ||
* ListNode(int x) : val(x), next(nullptr) {} | ||
* ListNode(int x, ListNode *next) : val(x), next(next) {} | ||
* }; | ||
*/ | ||
class Solution { | ||
public: | ||
void reorderList(ListNode* head) { | ||
ListNode *slow = head, *fast = head; | ||
for(; fast && fast->next; slow = slow->next, fast = fast->next->next); | ||
ListNode *head1 = head; | ||
ListNode *head2 = slow->next; | ||
slow->next = nullptr; | ||
|
||
// reverse list2 | ||
ListNode *nextNode = nullptr; | ||
for(ListNode *cur = head2; cur != nullptr;) { | ||
ListNode *curNext = cur->next; | ||
cur->next = nextNode; | ||
nextNode = cur; | ||
cur = curNext; | ||
} | ||
head2 = nextNode; | ||
|
||
// traverse list1 to insert | ||
for(ListNode *ptr1 = head1, *ptr2 = head2; ptr1 && ptr2;) { | ||
ListNode *ptr1Next = ptr1->next, *ptr2Next = ptr2->next; | ||
ptr1->next = ptr2; | ||
ptr2->next = ptr1Next; | ||
ptr1 = ptr1Next; | ||
ptr2 = ptr2Next; | ||
} | ||
} | ||
}; |