File tree 1 file changed +61
-0
lines changed
1 file changed +61
-0
lines changed Original file line number Diff line number Diff line change
1
+ /* *
2
+ * Definition for singly-linked list.
3
+ * struct ListNode {
4
+ * int val;
5
+ * ListNode *next;
6
+ * ListNode(int x) : val(x), next(NULL) {}
7
+ * };
8
+ */
9
+ class Solution {
10
+ public:
11
+ ListNode *findMid (ListNode *head){
12
+ if (head == NULL ) return head;
13
+ ListNode *slow = head,*fast = head -> next;
14
+ while (fast && fast -> next){
15
+ slow = slow -> next;
16
+ fast = fast -> next -> next;
17
+ }
18
+ return slow;
19
+ }
20
+
21
+ ListNode *reverseList (ListNode *head){
22
+ ListNode *prev = NULL ;
23
+ while (head != NULL ){
24
+ ListNode *tmp = head -> next;
25
+ head -> next = prev;
26
+ prev = head;
27
+ head = tmp;
28
+ }
29
+ return prev;
30
+ }
31
+
32
+
33
+ void mergeList (ListNode *head, ListNode *tail){
34
+ ListNode *dummy = new ListNode (-1 );
35
+ int index = 0 ;
36
+ while (head && tail){
37
+ if (index %2 == 0 ){
38
+ dummy -> next = head;
39
+ head = head -> next;
40
+ }else {
41
+ dummy -> next = tail;
42
+ tail = tail -> next;
43
+ }
44
+ dummy = dummy -> next;// don't forget
45
+ index ++;
46
+ }
47
+ if (head != NULL )
48
+ dummy -> next = head;
49
+ if (tail != NULL )
50
+ dummy -> next = tail;
51
+ }
52
+
53
+
54
+ void reorderList (ListNode *head) {
55
+ if (head == NULL ) return ;
56
+ ListNode *mid = findMid (head);
57
+ ListNode *tail = reverseList (mid ->next );
58
+ mid-> next = NULL ; // break the head and tail
59
+ mergeList (head, tail);
60
+ }
61
+ };
You can’t perform that action at this time.
0 commit comments