Monday, June 20, 2016

328. Odd Even Linked List

My own solution:

1:  class Solution {  
2:  public:  
3:    ListNode* oddEvenList(ListNode* head) {  
4:      ListNode *oddDummy = new ListNode(-1);  
5:      ListNode *evenDummy = new ListNode(-1);  
6:      ListNode *cur = head, *oddCur = oddDummy, *evenCur = evenDummy;  
7:      int i = 1;  
8:      while (cur) {  
9:        if (i % 2 == 1) {  
10:          oddCur->next = cur;  
11:          oddCur = oddCur->next;  
12:        } else {  
13:          evenCur->next = cur;  
14:          evenCur = evenCur->next;  
15:        }  
16:        cur = cur->next;  
17:        i++;  
18:      }  
19:      if (oddCur) {  
20:        oddCur->next = evenDummy->next;  
21:      }  
22:      if (evenCur) {  
23:        evenCur->next = NULL;  
24:      }  
25:      return oddDummy->next;  
26:    }  
27:  };  

Top solution on Leetcode is much more concise.

1:  class Solution {  
2:  public:  
3:    ListNode* oddEvenList(ListNode* head) {  
4:      if (!head) return head;  
5:      ListNode *oddCur = head, *evenHead = oddCur->next, *evenCur = oddCur->next;  
6:      while (evenCur && evenCur->next) {  
7:        oddCur->next = oddCur->next->next;  
8:        evenCur->next = evenCur->next->next;  
9:        oddCur = oddCur->next;  
10:        evenCur = evenCur->next;  
11:      }  
12:      oddCur->next = evenHead;  
13:      return head;  
14:    }  
15:  };  

No comments:

Post a Comment