1. 程式人生 > >LeetCode : 24. 兩兩交換連結串列中的節點(Swap Nodes In Pairs)解答

LeetCode : 24. 兩兩交換連結串列中的節點(Swap Nodes In Pairs)解答

24. 兩兩交換連結串列中的節點

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

示例:

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

說明:

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

一、分析

圖示:

在這裡插入圖片描述

規律:

  1. 交換過程基本就是:
previous.next = pair1.next;
pair1.next = pair2.next;
pair2.next =
pair1;
  1. 注意處理連結串列頭部,previousnull 的情況
  2. 注意處理連結串列尾部,afternull 的情況
  3. 其餘就是一對對的遍歷連結串列即可

二、解答

/**
 * Copyright © 2018 by afei. All rights reserved.
 * 
 * @author: afei
 * @date: 2018年11月19日
 */

public class Solution {

    public static void main(String[] args) {
        // create a list
        ListNode head =
null; ListNode tail = null; for (int i = 1; i <= 20; i++) { ListNode node = new ListNode(i); if (head == null) { head = node; tail = node; } else { tail.next = node; tail = node; }
} // do swap head = swapPairs(head); // print list while (head != null) { System.out.print(head.val + " "); head = head.next; } } public static ListNode swapPairs(ListNode head) { if (head == null) { return null; } if (head.next == null) { return head; } // init ListNode result = head.next; ListNode pair1 = head; ListNode pair2 = head.next; ListNode previous = null; // swap pair1.next = pair2.next; pair2.next = pair1; previous = pair1; pair1 = pair1.next; while (pair1 != null) { pair2 = pair1.next; if (pair2 == null) { break; } // swap previous.next = pair2; pair1.next = pair2.next; pair2.next = pair1; previous = pair1; pair1 = pair1.next; } return result; } public static class ListNode { int val; ListNode next; ListNode(int x) { val = x; } } }

三、專案地址

https://github.com/afei-cn/LeetCode/tree/master/24.%20Swap%20Nodes%20In%20Pairs

四、原題地址

https://leetcode-cn.com/problems/swap-nodes-in-pairs/