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

LeetCode:Swap Nodes in Pairs

时间:2014-06-29 14:39:10      阅读:268      评论:0      收藏:0      [点我收藏+]

标签:des   art   c   for   leetcode   io   

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

标签:des   art   c   for   leetcode   io   

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

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