首页 > 其他 > 详细

lintcode-easy-Swap Nodes in Pairs

时间:2016-03-07 08:54:31      阅读:230      评论:0      收藏:0      [点我收藏+]

Given a linked list, swap every two adjacent nodes and return its head.

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

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */
public class Solution {
    /**
     * @param head a ListNode
     * @return a ListNode
     */
    public ListNode swapPairs(ListNode head) {
        // Write your code here
        if(head == null || head.next == null)
            return head;
        
        ListNode fakehead = new ListNode(0);
        fakehead.next = head;
        
        ListNode prev = fakehead;
        ListNode curr = head;
        ListNode next = head.next;
        
        while(next != null && next.next != null){
            curr.next = next.next;
            next.next = curr;
            prev.next = next;
            
            curr = curr.next;
            next = curr.next;
            prev = prev.next.next;
        }
        
        if(next != null){
            curr.next = next.next;
            next.next = curr;
            prev.next = next;
        }
        
        return fakehead.next;
    }
}

 

lintcode-easy-Swap Nodes in Pairs

原文:http://www.cnblogs.com/goblinengineer/p/5249354.html

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