Reorder List leetcode
2015-12-25 11:25
316 查看
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
链表操作的思路往往比较容易想,但是实现起来就非常复杂。
这里思路就是
1.将链表分为前后两部分
2.将后部分链表反转,这里反转我使用了一种新的方法(制造一个新的链表,将旧链表的结点依次添加到新链表的前端)
3.构造新的链表,前后两部分链表结点交替添加到新链表中
4.构造完成
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}.
链表操作的思路往往比较容易想,但是实现起来就非常复杂。
这里思路就是
1.将链表分为前后两部分
2.将后部分链表反转,这里反转我使用了一种新的方法(制造一个新的链表,将旧链表的结点依次添加到新链表的前端)
3.构造新的链表,前后两部分链表结点交替添加到新链表中
4.构造完成
void reorderList(ListNode* head) { if (head == nullptr || head->next == nullptr) return; // 分割前后两部分 ListNode *slow = head; ListNode *fast = head; while (fast->next != nullptr && fast->next->next != nullptr) { slow = slow->next; fast = fast->next->next; } ListNode *head1 = head; ListNode *head2 = slow->next; slow->next = nullptr; head = head1; // 逆置链表 ListNode *tail2 = head2; head2 = head2->next; tail2->next = nullptr; while (head2 != nullptr) { ListNode *temp = head2->next; head2->next = tail2; tail2 = head2; head2 = temp; } // 交替构造新链表 head2 = tail2; while (head2 != nullptr) { ListNode *temp = head1->next; head1->next = head2; head1 = temp; ListNode *temp2 = head2->next; head2->next = head1; head2 = temp2; } }
相关文章推荐
- picture
- python 代码格式化工具:YAPF
- grails 私有库相关设置
- Python&按键精灵自动化
- 进程的虚拟内存,物理内存,共享内存
- 第八章 引用:
- 仿微信朋友圈图片按下效果
- iOS获取视频图片(视屏截图)
- Installshield 打包安装包心得
- android studio常用快捷键
- 赶紧加入微软的官方论坛DTCC吧,小伙伴们!!!
- Linux查看进程启动时间
- 关于 <textarea ></textarea >标签在苹果微信浏览器出现 内阴影
- linux grep,sed,awk和diff的使用
- I do not want to inherit the child opacity from the parent in CSS(不想让子元素继承父元素的透明度)
- Java Servlet (1) —— Filter过滤请求与响应
- nginx服务器搭建及部署项目流程
- 记录-mysql的sql执行效率方法
- 中间件最喜欢干的事
- 打印助手-打印暂停/开始问题原因调研记录