首页 > 其他 > 详细

24. Swap Nodes in Pairs

时间:2019-01-30 12:02:10      阅读:126      评论:0      收藏:0      [点我收藏+]

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:

  • Your algorithm should use only constant extra space.
  • You may not modify the values in the list‘s nodes, only nodes itself may be changed.

迭代,记得画个图,不然会懵逼

class Solution {
    public ListNode swapPairs(ListNode head) {
            ListNode dummy = new ListNode(-1), pre = dummy;
        dummy.next = head;
        while (pre.next !=null && pre.next.next!=null) {
            ListNode t = pre.next.next;
            pre.next.next = t.next;
            t.next = pre.next;
            pre.next = t;
            pre = t.next;
        }
             return dummy.next;
    }
       
}

 

24. Swap Nodes in Pairs

原文:https://www.cnblogs.com/wentiliangkaihua/p/10337287.html

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