Reorder List
来源:互联网 发布:快速弄到钱网络偏门2万 编辑:程序博客网 时间:2024/06/07 02:34
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 {1,4,2,3}
.
Subscribe to see which companies asked this question.
解题技巧:
先将链表分成两部分,然后翻转链表后半部分,最后将两部分链表进行组合
代码:
#include <iostream>using namespace std;struct ListNode { int val; ListNode *next; ListNode(int x) : val(x), next(NULL) {}};void reorderList(ListNode* head){ ListNode *p, *q, *h2, *tmp; //求链表的长度 int len = 0, ll; p = head; while(p) { len ++; p = p->next; } if(len == 0 || len == 1) return; //将链表分成两半 p = head; ll = len%2 ? len/2+1: len/2; for(int i = 1; i < ll; i ++) { p = p->next; } h2 = p->next; p->next = NULL; //将后半部分链表翻转 p = h2; q = h2->next; h2->next = NULL; while(q != NULL) { tmp = q->next; q->next = p; p = q; q = tmp; } h2 = p; //合并 p = head, q = h2; ListNode *pn, *qn; while(q) { pn = p->next; qn = q->next; p->next = q; q->next = pn; p = pn; q = qn; }}int main(){ ListNode *head = NULL, *p; int x; while(cin >> x) { ListNode *tmp = new ListNode(x); if(head != NULL) tmp->next = head; head = tmp; } p = head; while(p) { cout<<p->val<<" "; p = p->next; } cout<<endl; reorderList(head); p = head; while(p) { cout<<p->val<<" "; p = p->next; } cout<<endl;}
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
- LRU缓存和实现
- CSS3媒体查询(MediaQuery)技术
- 集合1
- 找出其中有多少种字符,每种字符有几个,并打印出来
- A Dangerous Maze ( 期望 )
- Reorder List
- java串口通信之帧解析
- MySQL 5.7.18免安装版教程
- POJ3268 Silver Cow Party(最短路问题)
- PuTsangTo-单撸游戏开发02 测试场景与单轴移动
- Cookie与Session的区别
- 数组中只出现一次的数
- Javaweb开发入职第一天
- 解决使用小米手机调试android开发程序的问题