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

24. Swap Nodes in Pairs

时间:2019-01-30 13:05:10      阅读:123      评论:0      收藏:0      [点我收藏+]

标签:turn   only   ever   node   color   algorithm   nod   lin   tno   

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

标签:turn   only   ever   node   color   algorithm   nod   lin   tno   

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

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