leetcode_24. 两两交换链表中的节点

24. 两两交换链表中的节点

给定一个链表,两两交换其中相邻的节点,并返回交换后的链表。

你不能只是单纯的改变节点内部的值,而是需要实际的进行节点交换。

示例:

给定 1->2->3->4, 你应该返回 2->1->4->3.

解题:

public class ListNode {
    int val;
    ListNode next;

    ListNode(int x) {
        val = x;
    }
}

class Solution {
    public ListNode swapPairs(ListNode head) {
        // 递归
//        if (head == null || head.next == null) {
//            return head;
//        }
//        ListNode next = head.next;
//        head.next = swapPairs(next.next);
//        next.next = head;
//        return next;
    // 非递归
        ListNode pre = new ListNode(0);
        pre.next = head;
        ListNode temp = pre;
        while(temp.next != null && temp.next.next != null) {
         // 1
            ListNode start=tmp.next;
            // 2
            ListNode end=tmp.next.next;
            // 0->2
            tmp.next=end;
            // 1>3>4
            start.next=end.next;
            // 2>1>3>4
            end.next=start;
            // 1>3>4
            tmp=start;
        }
        return pre.next;

//
//        作者:guanpengchn
//        链接:https://leetcode-cn.com/problems/swap-nodes-in-pairs/solution/hua-jie-suan-fa-24-liang-liang-jiao-huan-lian-biao/
//        来源:力扣(LeetCode)
//        著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。
    }

    public static void main(String[] args) {
        ListNode node1 = new ListNode(1);
        ListNode node2 = new ListNode(2);
        ListNode node3 = new ListNode(3);
        ListNode node4 = new ListNode(4);
        node1.next = node2;
        node2.next = node3;
        node3.next = node4;
        ListNode listNode = new Solution().swapPairs(node1);
        while (listNode!=null){
         System.out.print(listNode.val+" -> ");
         listNode=listNode.next;
        }
    }
}

参考:图解算法