改变链表顺序
来源:互联网 发布:4g网络哪个运营商好 编辑:程序博客网 时间:2024/06/07 07:55
出自于CareerCup,原题如下:
Suppose that we have a sorted singly linked list with integer values. For example:
1 -> 2 -> 3 -> 4 -> 5 -> 6 -> 7
We want to change the pointers of this linked list so that it becomes:
7->1->6->2->5->3->4
我的思路是先把链表分为前后两部分,再把后一部分顺序颠倒,然后再把两部分交替着连成新的链表,这样空间复杂度和时间复杂度都可以接受。
长时间不用链表了写得有些乱,中途还写错了导致死循环或内存报错好几次|||
代码如下:
#ifndef NODEH#define NODEHclass node{public:int value;node *next;};#endif
#include "node.h"#include <iostream>using namespace std;int main(){node *head = new node();node *end = new node();node *current = head;int num;while(cin>>num){current->next = new node;current = current->next;current->value=num;}current->next=end;node *headr = head;node *endr = new node();node *headt = new node();node *endt = end;current = head;node* half = head;while((current->next!=end)&&(current!=end)){current=current->next->next;half=half->next;}headt->next = half->next;half->next = endr;node* former = headt;current = headt->next;while(current->next!=endt){node *temp = current->next;current->next = former;former=current;current = temp;}current->next=former;endt->next=current;node *current2 = endt->next;current = headr->next;node *nextt;node *nextr;while(current2->next!=headt){nextt=current2->next;nextr=current->next;current2->next=current;current->next=nextt;current=nextr;current2=nextt;}current2->next=current;current=endt;while(current->next!=endr){current = current->next;cout<<current->value<<" ";}cout<<endl;return 0;}
- 改变链表顺序
- 如何改变oracle表结构列顺序
- jquery的改变顺序
- fedora 改变启动顺序
- 【C#】改变物体顺序
- MySQL改变列顺序
- MySQL改变列顺序
- MySQL改变列顺序
- 在oracle中改变字段在表中的顺序
- oracle中改变字段在表中的顺序
- 在oracle中改变字段在表中的顺序
- 改变窗口层叠的顺序
- 改变字符串顺序(倒序)
- 如何改变输入法的顺序
- 改变linux模块加载顺序
- Fedora 16 改变启动顺序
- jQuery动态改变元素顺序
- 改变窗口层叠的顺序
- hdu 3752 Is the one been second-killed first?
- pat 1015
- 错误:字符文本中字符太多
- hdu题目分类
- 去除敏感关键字,替换关键字描红函数
- 改变链表顺序
- 深复制 浅复制 最简单的记忆法则
- Hoj 1833 Truck History
- UML——面向对象技术
- 储能元件
- 稀疏矩阵的存储格式(Sparse Matrix Storage Formats)
- hdu 4236 Repeating Characters
- UML小结 ---类图
- linux常用命令大全