( Leetcode 24) Swap Nodes in Pairs
来源:互联网 发布:数据分析平台交互设计 编辑:程序博客网 时间:2024/05/16 10:42
题目:Swap Nodes in Pairs
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.
解题思想:
首先应该设置一个空的头结点,为了处理头结点head方便,首先设置一个dummy结点。还有应该都会想到的是设置一个p和q结点,每次这两个交换,但是在交换的时候大家容易忘记的一点就是交换的时候首先假设p在q的前面,我们令 p.next = q.next,这样先删除 了q结点,接下来应该在p结点前面插入q结点,很多人往往直接令q.next = p了,这样做是不对的,因为会导致前面的链表断掉,正确的做法是严格遵守链表插入方法。设置一个pre结点,每次都会记录p结点的前一个结点,然后才能插入q结点。
下面看具体的java代码,应该会明白很多。
public class Solution { public ListNode swapPairs(ListNode head) { if( head == null || head.next == null ){ return head; } ListNode dummy = new ListNode(-1); dummy.next = head; ListNode pre = dummy, p = head, q = head.next; while( q != null ){ ListNode r = q.next; p.next = q.next; q.next = p; pre.next = q; //说明到头了,当链表结点个数为偶数个的时候,r == null标明链表到头了//当链表结点个数为奇数个的时候,r.next == null标明链表结点到头了。 if( r == null || r.next == null ){ break; } pre = pre.next.next; p = r; q = r.next; } return dummy.next; }}
程序运行时间0ms。
0 0
- LeetCode(24)Swap Nodes in Pairs
- [LeetCode 24] Swap Nodes in Pairs
- [leetcode 24]Swap Nodes in Pairs
- LeetCode | #24 Swap Nodes in Pairs
- [Leetcode 24 链表]Swap Nodes in Pairs
- leetcode 24 Swap Nodes in Pairs
- 【leetcode】【单链表】【24】Swap Nodes in Pairs
- Leetcode 24 Swap Nodes in Pairs
- Swap Nodes in Pairs - LeetCode 24
- LeetCode 24 - Swap Nodes in Pairs
- leetcode 24 -- Swap Nodes in Pairs
- LeetCode 24:Swap Nodes in Pairs
- leetcode-24Swap Nodes in Pairs
- leetcode 24: Swap Nodes in Pairs
- Leetcode#24 Swap Nodes in Pairs
- LeetCode 24: Swap Nodes in Pairs
- LeetCode(24) Swap Nodes in Pairs
- [Leetcode 24, Medium] Swap Nodes in Pairs
- shell脚本显示颜色
- iOS开发之判断手机号和邮箱的合法性
- 类与对象(1):补充
- Introduction to Linear Algebra 4ED 学习笔记(2)
- hdu1160 FatMouse's Speed 最长上升子序列 LIS
- ( Leetcode 24) Swap Nodes in Pairs
- 压缩感知重构算法之OLS算法python实现
- Cassandra原理介绍
- Codeforces--659E--New Reform(深搜好题)
- 浅谈SQL注入基础
- 宏的全解
- Android中Intent传递对象的两种方法(Serializable,Parcelable)
- Android开发之下载服务器上的一张图片到本地java代码实现HttpURLConnection
- Ubuntu使用MAC主题