leetcode143 Reorder List
2016-05-09 21:41
369 查看
Given a singly linked list L: L0→L1→…→Ln-1→Ln,
reorder it to: L0→Ln→L1→Ln-1→L2→Ln-2→…
You must do this in-place without altering the nodes' values.
For example,
Given
note:反转时,42要放在43前面;
reorder it to: L0→Ln→L1→Ln-1→L2→Ln-2→…
You must do this in-place without altering the nodes' values.
For example,
Given
{1,2,3,4}, reorder it to
{1,4,2,3}.
/** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode(int x) : val(x), next(NULL) {} * }; */ class Solution { public: void reorderList(ListNode* head) { //分段 ListNode *p1,*p2; p1=head; p2=head; if(!p2) return; p2=p2->next; if(!p2) return; while(p1&&p1->next&&p2&&p2->next) { p1=p1->next; p2=p2->next; if(p2) p2=p2->next; } if(p1) { p2=p1->next; p1->next=NULL; } p1=head; if(p1==p2) return; //反转 ListNode *tnode=p2; p2=p2->next; tnode->next=NULL; while(p2) { ListNode *temp=p2; p2=p2->next; temp->next=tnode; tnode=temp; } //连接 ListNode *t=tnode; while(p1) { if(t) { ListNode *p12=p1; p1=p1->next; ListNode *t2=t; t=t->next; t2->next=p12->next; p12->next=t2; } else break; } } };
note:反转时,42要放在43前面;
相关文章推荐
- 微信读书 iOS 性能优化总结
- 对用java语言生成pdf文件的一些补充
- Java学习-常用排序稳定性分析
- C#三十 Ado.net和XML
- C#三十 Ado.net和XML
- Spring 事务
- C#三十 Ado.net和XML
- PS基础知识一
- cqm 解题报告e
- shell日期的应用
- HDU-5536 Chip Factory (字典树)
- 【常用算法】KDTree,局部敏感哈希LSH,在基于最近邻的算法中,当N特别大的时候(TODO)
- 博弈论 取石子(一)
- C++_BFS求最短路径
- iOS assign copy retain...含义
- 在O(1)时间删除链表结点――13
- 05Android学习从零单排之Androidmultimedia(多媒体)
- JS日期对象扩展-日期格式化
- 从零开始nodejs系列文章
- Golang 模块扩展