Leetcode 328 Odd Even Linked List 链表
2016-01-16 17:33
267 查看
将链表节点序号(不是值)是偶数的放到链表后面, 如
Given
return
我首先统计了下链表的大小cnt,同时求出链表尾端end,
然后直接将每个链表节点序号是奇数的点后面的节点放到end后面去,
同时更新end,这样更新cnt/2次。
注意点:当链表长度小于 3的时候不需要做这样的操作。
这里在附上一段测试代码
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; } } }
相关文章推荐
- 258. Add Digits
- Nginx缓存[proxy cache、memcache]
- 根据excel中的列表值,导入注解单元写入到指定包下所有java类方法中
- Matlab Compiler或mcc的使用
- Windows 环境里下载及安装 GO
- STM32F207(3) SetSysClock
- iOS 异常处理@try,catch
- 设置navigationController的背景颜色和背景图片
- poj 2955 Brackets 区间DP
- DBConnection公共类的使用-------java操作数据库(3)
- extjs中的表格编辑
- linux上几款必须装的软件推荐
- 修练8年C++面向对象程序设计之体会之 命名约定及assert
- secure CRT can't connects to Ubuntu and Ubuntu can't connets to Internet
- 软件原型设计工具
- 1045-Acess denied for user:'root'@'192.100.1.243'(Using password:YES)
- 安全多线程例子
- bzoj3583: 杰杰的女性朋友 && 4362: Graph
- JAVA线程池原理以及常用线程池介绍
- 从一道题目验证Servlet单实例