[LeetCode] 24. Swap Nodes in Pairs
Posted aaronliu1991
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了[LeetCode] 24. Swap Nodes in Pairs相关的知识,希望对你有一定的参考价值。
成对交换节点。给一个linked list,请成对调换node。例子
Given1->2->3->4
, you should return the list as2->1->4->3
.
我的思路是迭代。依然是给一个dummy节点放在head节点之前,然后dummy.next是head节点,nextStart是第三个节点,需要交换的只是l2和l2.next。我画了一个示意图,这样不容易错。
dummy -> 1 -> 2 -> 3 -> 4l1 l2 ns
时间O(n)
空间O(1)
1 /** 2 * @param {ListNode} head 3 * @return {ListNode} 4 */ 5 var swapPairs = function(head) { 6 // corner case 7 if (head === null || head.next === null) { 8 return head; 9 } 10 11 // normal case 12 let dummy = new ListNode(0); 13 dummy.next = head; 14 let l1 = dummy; 15 let l2 = head; 16 while (l2 !== null && l2.next !== null) { 17 let nextStart = l2.next.next; 18 l1.next = l2.next; 19 l2.next.next = l2; 20 l2.next = nextStart; 21 l1 = l2; 22 l2 = l2.next; 23 } 24 return dummy.next; 25 };
Java实现
1 class Solution { 2 public ListNode swapPairs(ListNode head) { 3 // corner case 4 if (head == null || head.next == null) { 5 return head; 6 } 7 8 // normal case 9 ListNode dummy = new ListNode(0); 10 dummy.next = head; 11 ListNode l1 = dummy; 12 ListNode l2 = head; 13 while (l2 != null && l2.next != null) { 14 ListNode nextStart = l2.next.next; 15 l1.next = l2.next; 16 l2.next.next = l2; 17 l2.next = nextStart; 18 l1 = l2; 19 l2 = l2.next; 20 } 21 return dummy.next; 22 } 23 }
以上是关于[LeetCode] 24. Swap Nodes in Pairs的主要内容,如果未能解决你的问题,请参考以下文章
Leetcode-24 Swap Nodes in Pairs
LeetCode 24 Swap Nodes in Pairs
Leetcode24. Swap Nodes in Pairs
Leetcode24. Swap Nodes in Pairs