Leetcode 328 Odd Even Linked List 链表

Given 1->2->3->4->5->NULL,
return 1->3->5->2->4->NULL.

就是将序号为单数的放在前面,而序号为偶数的放在后面

我的方法是讲序号为偶数的的插入到链表末尾

 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* oddEvenList(ListNode* head) {
12         if(!head) return head;//空链表返回
13         ListNode* last = head;
14         int cnt = 1;
15         for(; last->next; last = last->next, ++cnt);
16         if(cnt < 3) return head;//链表长度小于3返回
17         ListNode* now = head;
18         ListNode* end = last;
19             
20         for(int i = 0; i< cnt/2; now = now->next, ++i){
21             
22             ListNode* next = now->next;
23             now->next = next->next;
24                 
25             end->next = next;
26             next->next = NULL;
27                 
28             end = next;
29             
30         }
31         return head;
32     }
33 };

 

posted @ 2016-02-24 10:28  Breeze0806  阅读(132)  评论(0编辑  收藏  举报