1. 程式人生 > >LeedCode---【24】【兩兩交換連結串列節點】

LeedCode---【24】【兩兩交換連結串列節點】

一、原題要求:

給定一個連結串列,兩兩交換其中相鄰的節點,並返回交換後的連結串列。

示例:

給定 1->2->3->4, 你應該返回 2->1->4->3

說明:

  • 你的演算法只能使用常數的額外空間。
  • 你不能只是單純的改變節點內部的值,而是需要實際的進行節點交換。

解題思路:
使用一個新的節點pre來輔助操作,對要進行交換的連結串列,每兩個的位置進行交換,
 並且把交換後的結點接到pre的連結串列上,直到所有的結點都處理完。

因為比較簡單就直接上程式碼了

二、程式碼實現:

/**
 * @ClassName: Main
 * @Description: TODO
 * @Author: Mr.Ye
 * @Data: 2018-11-17 19:59
 * @Version: 1.0
 **/
class ListNode {
    int val;
    ListNode next;

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

class Solution {
    public ListNode swapPairs(ListNode head) {
        ListNode old = new ListNode(0);
        old.next = head;
        ListNode pre = old;
        while (pre.next != null && pre.next.next != null){
            ListNode node1 = pre.next;
            ListNode node2 = node1.next;
            ListNode late = node2.next;

            pre.next = node2;
            node2.next = node1;
            node1.next = late;
            pre = node1;
        }
        return old.next;
    }
}

public class Main {
    public static void main(String[] args) {
        ListNode n1 = new ListNode(1);
        ListNode n2 = new ListNode(4);
        ListNode n3 = new ListNode(3);
        ListNode n4 = new ListNode(2);
        ListNode n5 = new ListNode(5);
        ListNode n6 = new ListNode(2);
        n1.next = n2;
        n2.next = n3;
        n3.next = n4;
        n4.next = n5;
        n5.next = n6;
        System.out.println("初始連結串列:");
        print(n1);

        Solution solution = new Solution();
        System.out.println("最終連結串列:");
        print(solution.swapPairs(n1));
    }

    public static void print(ListNode head) {
        for (ListNode temp = head; temp != null; temp = temp.next) {
            System.out.print(temp.val + "->");
        }
        System.out.println("null");
    }
}