328. 奇偶链表
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 //建立两个虚拟节点,分别存放节点的奇偶 10 class Solution 11 { 12 public: 13 ListNode* oddEvenList(ListNode* head) 14 { 15 ListNode* dummy1 = new ListNode(-1); 16 ListNode* dummy2 = new ListNode(-1); 17 ListNode* pre1 = dummy1; 18 ListNode* pre2 = dummy2; 19 20 ListNode* cur = head; 21 while(cur && cur->next) 22 { 23 pre1->next = cur; 24 cur = cur->next; 25 pre1 = pre1->next; 26 27 pre2->next = cur; 28 cur = cur->next; 29 pre2 = pre2->next; 30 } 31 if(cur) 32 { 33 pre1->next = cur; 34 pre1 = pre1->next; 35 } 36 pre1->next = dummy2->next; 37 pre2->next = NULL; 38 return dummy1->next; 39 } 40 };
Mamba never out

浙公网安备 33010602011771号