码迷,mamicode.com
首页 > 其他好文 > 详细

Leetcode 328 Odd Even Linked List 链表

时间:2016-02-24 10:55:48      阅读:134      评论:0      收藏:0      [点我收藏+]

标签:

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 };

 

Leetcode 328 Odd Even Linked List 链表

标签:

原文地址:http://www.cnblogs.com/onlyac/p/5212048.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!