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

[LeetCode]24 Swap Nodes in Pairs

时间:2015-01-02 16:12:21      阅读:151      评论:0      收藏:0      [点我收藏+]

标签:leetcode

https://oj.leetcode.com/problems/swap-nodes-in-pairs/

http://fisherlei.blogspot.com/2013/01/leetcode-swap-nodes-in-pairs.html

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) {
 *         val = x;
 *         next = null;
 *     }
 * }
 */
public class Solution {
    public ListNode swapPairs(ListNode head) {
        
        if (head == null || head.next == null)
            return head;
        
        ListNode a = head;
        ListNode b = head.next;
        ListNode newhead = b;
        ListNode pre = null;
        
        while (a != null && b != null)
        {
            // a -> b
            // swap a and b
            ListNode next = b.next;
            a.next = next;
            b.next = a;
            if (pre != null)
                pre.next = b;
            pre = a;
            a = next;
            if (a != null)
                b = a.next;
        }

        return newhead;        
    }
}


[LeetCode]24 Swap Nodes in Pairs

标签:leetcode

原文地址:http://7371901.blog.51cto.com/7361901/1598423

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