首页 > 其他 > 详细

LeetCode:Swap Nodes in Pairs

时间:2014-06-29 14:12:09      阅读:390      评论: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.

这道题非常简单,如果n>=2,先把开始的2个结点交换,把head指向开头。

之后只要后面有2个结点,就交换,其关键是2个结点的前一个结点和后一个结点,前一个结点要指向交换后的第一个结点,2个结点交换后的第2个结点要指向他们的后一个结点。其他没有什么。


public class Solution {
     public ListNode swapPairs(ListNode head) {
        if(head==null||head.next == null)return head;
        ListNode start = head;
        ListNode temp = start;
        start = start.next;
        ListNode next = start.next;
        start.next = temp;
        temp.next = next;
        head = start;
        start = next;
        ListNode former = temp;
        while(start!=null&&start.next!=null)
        {
            swap(former,start);
            former = start;
            start = start.next;
        }
        return head;
       
    }
    public void swap(ListNode former,ListNode node)
    {
        if(node==null||node.next==null)return;
        else
        {
            ListNode temp = node;
            node = node.next;
            ListNode next = node.next;
            former.next=node;
            node.next = temp;
            temp.next =next;
        }
    }
}

LeetCode:Swap Nodes in Pairs,布布扣,bubuko.com

LeetCode:Swap Nodes in Pairs

原文:http://www.cnblogs.com/jessiading/p/3755444.html

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