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

leetcode-24 Swap Nodes in Pairs

时间:2015-05-06 15:07:39      阅读:139      评论:0      收藏:0      [点我收藏+]

标签:

问题描述:

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

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

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

问题分析:

每一次循环指针变换如下图:除了需要调换C和D的顺序外,还要注意上一次循环的尾节点pre即途中的A,其next当前指向C,应将其指向翻转后的D;
技术分享
代码:

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */
public class Solution {
    public ListNode swapPairs(ListNode head) {
        if(head == null || head.next == null)
            return head;
        ListNode result = head.next;

        ListNode preNode = null;//前一循环的尾节点
        ListNode ANode   = null;//循环的左节点
        ListNode BNode   = null;//循环的右节点  

        while(head != null && head.next != null)
        {
            ANode = head;
            BNode = head.next;

            //为下一循环准备
            head = BNode.next;
            if(preNode != null)
                preNode.next = BNode;//将前一个循环尾节点指向本循环翻转后的头结点
            preNode = ANode;

            //翻转A,B
            ANode.next = BNode.next;
            BNode.next = ANode; 
        }   
        return result;     
    }
}

leetcode-24 Swap Nodes in Pairs

标签:

原文地址:http://blog.csdn.net/woliuyunyicai/article/details/45535433

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