File tree Expand file tree Collapse file tree 1 file changed +61
-0
lines changed Expand file tree Collapse file tree 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() : val(0), next(nullptr) {}
7
+ * ListNode(int x) : val(x), next(nullptr) {}
8
+ * ListNode(int x, ListNode *next) : val(x), next(next) {}
9
+ * };
10
+ */
11
+ class Solution {
12
+ public:
13
+ ListNode* rev (ListNode* head){
14
+ if (head == NULL ){
15
+ return NULL ;
16
+ }
17
+
18
+ ListNode* prev = NULL ;
19
+ ListNode* curr = head;
20
+ ListNode* next;
21
+ while (curr){
22
+ next = curr -> next;
23
+ curr -> next = prev;
24
+ prev = curr;
25
+ curr = next;
26
+ }
27
+
28
+ return prev;
29
+ }
30
+ void reorderList (ListNode* head) {
31
+ if (head==NULL ||head->next ==NULL ||head->next ->next ==NULL ){
32
+ return ;
33
+ }
34
+ // / Find middle Node
35
+ ListNode* slow = head;
36
+ ListNode* fast = head -> next;
37
+
38
+ while (fast && fast -> next){
39
+ slow = slow -> next;
40
+ fast = fast -> next -> next;
41
+ }
42
+
43
+ ListNode* secHead = slow -> next;
44
+ slow -> next = NULL ;
45
+
46
+ // / Reverse 2nd list
47
+ secHead = rev (secHead);
48
+ ListNode* tmp1 = head;
49
+ ListNode* tmp2 = secHead;
50
+
51
+ while (tmp1 && tmp2){
52
+ ListNode* curr1 = tmp1 -> next;
53
+ ListNode* curr2 = tmp2 -> next;
54
+
55
+ tmp1 -> next = tmp2;
56
+ tmp2 -> next = curr1;
57
+ tmp1 = curr1;
58
+ tmp2 = curr2;
59
+ }
60
+ }
61
+ };
You can’t perform that action at this time.
0 commit comments