Reorder List
来源:互联网 发布:什么天气软件最准确 编辑:程序博客网 时间:2024/06/06 03:40
Description:
Given a singly linked list L : L 0 → L 1 → · · · → L n−1 → L n , reorder it to: L 0 → L n → L 1 →
L n−1 → L 2 → L n−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}.
分析:
题目规定要 in-place,也就是说只能使用 O(1) 的空间。
可以找到中间节点,断开,把后半截单链表 reverse 一下,再合并两个单链表。
#include <iostream>#include <limits.h>using namespace std;struct LNode{ int val; LNode *next; LNode(int x):val(x),next(nullptr) {}};class Solution{ public: LNode *reorderList(LNode *L) { if (L == nullptr || L->next == nullptr) return L; LNode *slow = L, *fast = L; LNode *prev = nullptr; while (fast && fast->next) { prev = slow; slow = slow->next; fast = fast->next->next; } prev->next = nullptr; slow = reverseList(slow); //merge two lists LNode *p1 = L, *p2 = slow; LNode *p1Next = nullptr, *p2Next = nullptr; while (p1->next) { p1Next = p1->next; p2Next = p2->next; p2->next = p1->next; p1->next = p2; p1 = p1Next; p2 = p2Next; } p1->next = p2; return L; } LNode *reverseList(LNode *List) { LNode *head = List; LNode *pre = List; LNode *cur = pre->next; LNode *curNext = nullptr; while (cur) { curNext = cur->next; cur->next = pre; pre = cur; cur = curNext; } head->next = nullptr; return pre; }};int main(){ LNode *List = new LNode(INT_MIN); // create head node cout<<"Input the number: "<<endl; int n; cin>>n; LNode *ptr = List; for (int i = 1; i <= n; ++i) { ptr->next = new LNode(i); ptr = ptr->next; cout<<ptr->val; if (i < n) cout<<"->"; } cout<<endl; Solution solution; LNode *result = solution.reorderList(List->next); delete List; // release ptr = result; while (result) // output and release the list { ptr = result->next; cout<<result->val; if (ptr) cout<<"->"; delete result; result = ptr; } cout<<endl; return 0;}
0 0
- Reorder List
- Reorder List
- Reorder List
- Reorder List
- Reorder List
- Reorder List
- Reorder List
- Reorder List
- Reorder List
- Reorder List
- Reorder List
- Reorder List
- Reorder List
- Reorder List
- Reorder List
- Reorder List
- Reorder List
- Reorder List
- 练习1-g
- knockoutJS学习指南
- ld: 1 duplicate symbol for architecture arm64 clang: error: linker command failed with exit code 1 (
- MySQL max_allowed_packet设置及问题
- 剑指offer-面试题17:合并两个排序的链表
- Reorder List
- 抽象类和接口
- Spring与redis的集成的笔记
- LayoutInflater
- spring实现AOP的两种方式以及实现动态代理方式
- 数据转换工具类汇总
- Android 自定义相机开发(支持前置,后置摄像头,可以自动聚焦,保存和显示图片)
- Linux安装Tomcat
- 数据库SQL优化大总结之 百万级数据库优化方案