Swap Nodes in Pairs
来源:互联网 发布:便宜好用的汽车 知乎 编辑:程序博客网 时间:2024/05/22 00:36
Description:
Given a linked list, swap every two adjacent nodes and return its head.
For example, Given 1->2->3->4, you should return the list as 2->1->4->3.
Your algorithm should use only constant space. You may not modify the values in the list, only nodes
itself can be changed.
#include <iostream>#include <limits.h>using namespace std;class LNode{public: int val; LNode *next; LNode(int x):val(x),next(nullptr) { }};class Solution{ public: LNode *swapNodes(LNode *L) { if (L == nullptr || L->next == nullptr || L->next->next == nullptr) return L; LNode *pre = L; LNode *cur = pre->next; LNode *nex = cur->next; L = nex; while (1) { pre->next = nex; cur->next = nex->next; nex->next = cur; if (cur->next == nullptr) break; pre = cur; cur = cur->next; if (cur->next == nullptr) break; nex = cur->next; } return L; }};int main(){ LNode *List = new LNode(INT_MIN); //create head node cout<<"Input the number: "<<endl; int num; cin>>num; LNode *ptr = List; cout<<"Input the node: "<<endl; //尾插法创建并输出链表; for (int i = 0; i < num; ++i) { int value; cin>>value; ptr->next = new LNode(value); ptr = ptr->next; cout<<ptr->val; if (i < num-1) cout<<"->"; } cout<<endl; Solution solution; LNode *ret = solution.swapNodes(List); LNode *del = nullptr; while(ret != nullptr) //输出并释放链表 { del = ret; cout<<ret->val; if (ret->next != nullptr) cout<<"->"; ret = ret->next; delete del; } delete List; return 0;}
0 0
- Swap Nodes in Pairs
- Swap Nodes in Pairs
- Swap Nodes in Pairs
- Swap Nodes in Pairs
- Swap Nodes In Pairs
- Swap Nodes in Pairs
- Swap Nodes in Pairs
- Swap Nodes in Pairs
- Swap Nodes in Pairs
- Swap Nodes in Pairs
- Swap Nodes in Pairs
- Swap Nodes in Pairs
- Swap Nodes in Pairs
- Swap Nodes in Pairs
- Swap Nodes in Pairs
- Swap Nodes in Pairs
- Swap Nodes in Pairs
- Swap Nodes in Pairs
- 银行家算法(1)——概念与举例说明(多进程管理资源分配避免死锁)
- leetcode_065 Valid Number
- SVM-4-核函数
- windows SDK程序的模板
- 使用JsonP进行跨域请求
- Swap Nodes in Pairs
- stm32f103 RTC周期性待机唤醒(一)
- HDU 5646 DZY Loves Partition (数学)
- Oracle数据仓库创建教程
- 1000搬桌子问题 ACID 00729209
- C#拼音联想式选择
- 目标跟踪:背景建模重要博文
- opencv全屏显示
- Python 数学运算