码迷,mamicode.com
首页 > 其他好文 > 详细

[LeetCode] 24. Swap Nodes in Pairs

时间:2020-04-12 14:57:23      阅读:75      评论:0      收藏:0      [点我收藏+]

标签:实现   The   style   UNC   code   ||   pairs   normal   swap   

成对交换节点。给一个linked list,请成对调换node。例子

Given 1->2->3->4, you should return the list as 2->1->4->3.

我的思路是迭代。依然是给一个dummy节点放在head节点之前,然后dummy.next是head节点,nextStart是第三个节点,需要交换的只是l2和l2.next。我画了一个示意图,这样不容易错。

dummy -> 1 -> 2 -> 3 -> 4
l1              l2            ns

时间O(n)

空间O(1)

JavaScript实现

 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

标签:实现   The   style   UNC   code   ||   pairs   normal   swap   

原文地址:https://www.cnblogs.com/aaronliu1991/p/11796069.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!