Swap Nodes in Pairs
来源:互联网 发布:appserv怎么进入mysql 编辑:程序博客网 时间:2024/05/29 10:01
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
思路:
题目的要求是要将链表中每两个节点进行交换(不能仅仅交换值),比如节点1节点2交换,节点3和节点4交换。
用到的操作和链表逆置那道题差不多,这种题目只要画画图,把指针依次怎么指向的过程搞清楚就行了。这道题因为头结点
会发生改变,所以使用一个dummy节点会比较方便操作。
其中:dummy.next = head,pre = dummy,cur1 = pre.next,cur2 = cur1.next。现在画图来演示交换过程。
class Solution { public ListNode swapPairs(ListNode head) { if(head == null) { return null; } ListNode dummy = new ListNode(0); dummy.next = head; ListNode pre = dummy; ListNode cur1 = pre.next; ListNode cur2 = cur1.next; while(cur2 != null && cur1 != null) { ListNode tmp = cur2.next; pre.next = cur2; cur2.next = cur1; cur1.next = tmp; pre = cur1; cur1 = cur1.next; if(cur1 != null) { cur2 = cur1.next; } } return dummy.next; } }
阅读全文
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
- Servlet从入门开始学习(一)
- vue-Resource(与后端数据交互)
- java基于索引对List进行分批处理
- python中的number数字
- Tablayout+Viewpager+recyclerview简单实现
- Swap Nodes in Pairs
- Quartz中时间参数说明 即Cron表达式
- PMCAFF产品众测 | 对话随手攒CEO聊聊这款产品的设计、推广和改进(活动已结束)
- 极线约束
- 第五周 【项目2
- 【李叫兽】如何识别故作高深的空话
- python 2.7.12报ImportError: No module named _socket
- 下拉选项框联动
- android学习笔记(四)