24. Swap Nodes in Pairs

来源:互联网 发布:周立功单片机笔试题目 编辑:程序博客网 时间:2024/06/05 18:34

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.

题目要求:不能改变节点内的值,只能改变节点的位置。

方法1:

public class Solution {
    public ListNode swapPairs(ListNode head) {
    if(head==null||head.next==null)
    return head;
        ListNode swap=head;
        ListNode t=null;
        ListNode h=head;
        t=swap.next;
        swap.next=t.next;
        t.next=swap;
        head=t;
        while(swap.next!=null&&swap.next.next!=null){ 
        h=swap;
             swap=swap.next;
             t=swap.next;
             swap.next=t.next;
             t.next=swap;
             h.next=t;  
        }
        return head;
    }
}

方法2:

public ListNode swapPairs(ListNode head) {

        if(head == null || head.next == null){
            return head;
        }
        ListNode slow = head;
        ListNode fast = head.next;
        slow.next = fast.next;
        fast.next = slow;
        head = fast;
        slow.next = swapPairs(slow.next);
        return head;

    }


0 0
原创粉丝点击