leetcode Reorder List
2013-11-24 15:59
453 查看
Reorder List
Total Accepted: 2069 Total Submissions: 11880My SubmissionsGiven 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
{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: ListNode* reverse(ListNode* head) { ListNode* prev = NULL, *cur = head, *next = NULL; while (cur != NULL) { next = cur->next; cur->next = prev; prev = cur; cur = next; } return prev; } void reorderList(ListNode *head) { if (head == NULL || head->next == NULL || head->next->next == NULL) return; ListNode *slow = head, *fast = head; while (fast != NULL && fast->next != NULL && fast->next->next != NULL) { slow = slow->next; fast = fast->next->next; } ListNode *l2 = reverse(slow->next), *l1 = head, *l1next = NULL, *l2next = NULL; slow->next = NULL; while (l2 != NULL) { l1next = l1->next; l1->next = l2; l2next = l2->next; l2->next = l1next; l1 = l1next; l2 = l2next; } } };Reverse the second half string.
相关文章推荐
- 给我一篇假论文,我能骗倒半个地球
- 班级学生德育量化管理系统_德育积分学分考核系统_学生操行日常行为规范考核系统
- windows server 2012 动态访问控制
- 21-JAVA面向对象-继承-final关健字,instanceof关健字
- 【opencv】特征点检测方法--GFTT,SIFT,FAST,SURF
- Python基础学习笔记之(一)
- [译]GotW #89 Smart Pointers
- 【Android Developers Training】 4. 启动另一个Activity
- mapreduce 类型配置
- erb文件与rhtml文件的区别
- LeetCode Longest Common Prefix 最长前缀
- 一定要用数组标记|xi-xj|,不然会超时
- ssh上传并显示图片
- HTML复选框和单选框 radio checkbox
- tslib编译与安装-----arm----交叉编译
- Linux下LAPM的安装和配置
- 《#诗盗#~日光浴》
- 浙工ACM1295
- HDU 1172 猜数字
- 树状数组(二进制索引树)