首页 > 其他 > 详细

Leetcode 24. Swap Nodes in Pairs

时间:2018-02-04 21:39:31      阅读:236      评论:0      收藏:0      [点我收藏+]

技术分享图片

思路:添加头节点,依次反转相邻元素,保持反转后的最后一个指针pre,当前被反转的第一个元素的指针cur,当前被反转的第二个元素的指针next(如果存在的话)。反转的思路和92. Reverse Linked List II差不多,只不过pre要移动。

 1 /**
 2  * Definition for singly-linked list.
 3  * public class ListNode {
 4  *     int val;
 5  *     ListNode next;
 6  *     ListNode(int x) { val = x; }
 7  * }
 8  */
 9 class Solution {
10     public ListNode swapPairs(ListNode head) {
11         if(head == null) return head;
12         ListNode dummy = new ListNode(0);
13         dummy.next = head;
14         ListNode pre = dummy, cur = head;
15         while(cur != null && cur.next != null) {//保证有2个可以被反转的元素
16             ListNode next = cur.next;
17             cur.next = next.next;
18             next.next = cur;
19             pre.next = next;
20             pre = cur;
21             cur = cur.next;
22         }
23         return dummy.next;
24     }
25 }

 

Leetcode 24. Swap Nodes in Pairs

原文:https://www.cnblogs.com/Deribs4/p/8414131.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!