Swap Nodes in Pairs
来源:互联网 发布:钉钉打卡软件 编辑:程序博客网 时间:2024/04/30 11:32
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.
这个问题我们先建一个头结点,这样可以统一操作,每一步就那么几个操作,见图。
这样就不用特别处理第一结点,好了看明白这个图说的步骤就代码。
class Solution {public:ListNode *swapPairs(ListNode *head) {if(head == NULL || head->next == NULL)return head;ListNode *pre, *tail;ListNode *new_head = new ListNode(-1);new_head->next = head;pre = new_head;while(pre->next && pre->next->next){tail = pre->next->next;pre->next->next = tail->next;tail->next = pre->next;pre->next = tail;pre = tail->next;}pre = new_head;new_head = new_head->next;delete pre;return new_head;}};
leetcode里有好多链表题,这里是创建链表的函数,想自己测试的在这里下:创建链表函数
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
- OpenCV成长之路(6):数学形态学基本操作及其应用
- 关于ffmpeg如何提取视频的关键帧的问题
- repo新的下载地址
- make file中ifneq含义
- Revit二次开发首次使用
- Swap Nodes in Pairs
- java web开发 高并发处理
- diff 和 patch
- 统计分词/无字典分词学习(5):候选片段的过滤方法,边界稳定性
- 使用Rich Edit 控件需要调用 AfxInitRichEdit2()
- AFDX总线协议规范
- zlib的安装与使用
- JavaWeb -- Servlet Filter 过滤器
- SVN 项目管理方法