您的位置:首页 > 其它

Leetcode 328 Odd Even Linked List 链表

2016-01-16 17:33 267 查看
将链表节点序号(不是值)是偶数的放到链表后面, 如

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

我首先统计了下链表的大小cnt,同时求出链表尾端end,

然后直接将每个链表节点序号是奇数的点后面的节点放到end后面去,

同时更新end,这样更新cnt/2次。

注意点:当链表长度小于 3的时候不需要做这样的操作。

/**
* Definition for singly-linked list.
* struct ListNode {
*     int val;
*     ListNode *next;
*     ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode* oddEvenList(ListNode* head) {
if(!head) return head;
ListNode* last = head;
int cnt = 1;
for(; last->next; last = last->next, ++cnt);
if(cnt < 3) return head;
ListNode* now = head;
ListNode* end = last;

for(int i = 0; i< cnt/2; now = now->next, ++i){

ListNode* next = now->next;
now->next = next->next;

end->next = next;
next->next = NULL;

end = next;

}
return head;
}
};


这里在附上一段测试代码

int main(){
int n;
while(scanf("%d",&n)){
ListNode* head = new ListNode(1);
ListNode* node= head;
for(int i = 2; i<=n; ++i ){
ListNode* now = new ListNode(i);
node->next = now;
node = now;
}
Solution s;
s.oddEvenList(head);
for(node = head; node; node = node ->next){
printf("%d ",node->val);
}
puts("");
for(node = head; node; ){
ListNode* now = node;
node = node ->next;
delete now;
}
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: