24. Swap Nodes in Pairs

题目

原始地址:

/**
 * 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) {
        
    }
}

描述

给定一个单链表,交换每两个相邻的节点并返回新链表的头。

分析

题目比较简单,正确交换相邻节点即可,分别给出递归和循环两种解法。

解法1

/**
 * 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){
            ListNode tmp = head.next;
            head.next = swapPairs(head.next.next);
            tmp.next = head;
            return tmp;
        }
        return head;
    }
}

解法2

/**
 * 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) {
        ListNode dummy = new ListNode(0), tail = dummy, curr = head, next;
        dummy.next = head;
        while (curr != null && curr.next != null) {
            next = curr.next.next;
            tail.next = curr.next;
            curr.next.next = curr;
            curr.next = next;
            curr = next;
            tail = tail.next.next;
        }
        return dummy.next;
    }
}
posted @ 2017-05-09 18:26  北冥尝有鱼  阅读(104)  评论(0编辑  收藏  举报