脚本宝典收集整理的这篇文章主要介绍了[LintCode] Swap Nodes in Pairs,脚本宝典觉得挺不错的,现在分享给大家,也给大家做个参考。
PRoblem
Given a linked list, swap every two adjacent nodes and return ITs head.
Example
Given 1->2->3->4, you should return the list as 2->1->4->3.
Note
指针为p
,我们选择swap的两个结点是p.next
和p.next.next
。要注意while
循环的边界条件,这两个结点不能为空。主要思路是先用next
和temp
两个新结点去保存p.next.next.next
和p.next
两个结点。完成交换之后,连接temp
和next
,并让p
前进至此时的temp
结点。
Solution
public class Solution {
public ListNode swapPairs(ListNode head) {
if (head == null) return head;
ListNode dummy = new ListNode(0);
dummy.next = head;
ListNode p = dummy;
while (p.next != null && p.next.next != null) {
ListNode next = p.next.next.next;
ListNode temp = p.next;
p.next = p.next.next;
p.next.next = temp;
temp.next = next;
p = temp;
}
return dummy.next;
}
}
OR
public class Solution {
public ListNode swapPairs(ListNode head) {
if (head == null || head.next == null) return head;
ListNode dummy = new ListNode(0);
dummy.next = head;
ListNode cur = dummy;
while (cur.next != null && cur.next.next != null) {
ListNode n1 = cur.next;
ListNode n2 = cur.next.next;
cur.next = n2;
n1.next = n2.next;
n2.next = n1;
cur = n1;
}
return dummy.next;
}
}
以上是脚本宝典为你收集整理的[LintCode] Swap Nodes in Pairs全部内容,希望文章能够帮你解决[LintCode] Swap Nodes in Pairs所遇到的问题。
本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。