Reorder List问题及解法
来源:互联网 发布:大华网络客户端软件 编辑:程序博客网 时间:2024/05/18 17:59
问题描述:
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.
示例,
Given {1,2,3,4}
, reorder it to {1,4,2,3}
.
问题分析:
对于此类问题,统计结点数目,并找到中间结点mid,对mid后的结点依次插入即可。
例如
l0,l1,l2,l6,l3,l4,l5这个链表来说,l6是mid,之后就是将l5插入l0和l1之间,l4插入l1和l2之间,l3插入l2和l6之间。
过程详见代码:
/** * 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) { vector<ListNode*> res;ListNode * temp = head;int num = 0;while (temp){num++;res.emplace_back(temp);temp = temp->next; }temp = head;for (int i = 1; i <= num / 2; i++){if (temp->next == res[num - i]) return;res[num - i]->next = temp->next;temp->next = res[num - i];temp = res[num - i]->next;res[num - i - 1]->next = NULL;} }};
阅读全文
0 0
- Reorder List问题及解法
- Rotate List问题及解法
- Partition List问题及解法
- Sort List问题及解法
- Linked List Cycle问题及解法
- Palindrome Linked List问题及解法
- Reverse Linked List II问题及解法
- Linked List Cycle II问题及解法
- Insertion Sort List问题及解法
- Linked List Random Node问题及解法
- Odd Even Linked List问题及解法
- Flatten Nested List Iterator问题及解法
- LeetCode Reorder List O(n) space空间解法
- Remove Nth Node From End of List问题及解法
- Remove Duplicates from Sorted List问题及解法
- Remove Duplicates from Sorted List II问题及解法
- Convert Sorted List to Binary Search Tree问题及解法
- Flatten Binary Tree to Linked List问题及解法
- new delete和malloc free的区别
- hdu1074 状压DP
- 母函数模板
- 员工持股一定提高公司绩效吗?其实这并不是个充要条件
- svn
- Reorder List问题及解法
- cannot resolve symbol 'Strings'
- thinking in java 4
- WKWebView的OC和JS交互
- lombok自动生成set,get,方法
- Spring Boot 快速入门
- CI框架去除index.php(Nginx)
- python基础面试必备(一)
- 解决127.0.0.1无法访问本地tomcat服务器