ペアワイズ リンク リスト スワップ
7338 ワード
説明
リンクされたリストを指定して、隣接する 2 つのノードごとに交換し、その先頭を返します.
例 1:
Input: head = [1,2,3,4]
Output: [2,1,4,3]
例 2:
Input: head = []
Output: []
例 3:
Input: head = [1]
Output: [1]
制約:
Input: head = [1,2,3,4]
Output: [2,1,4,3]
Input: head = []
Output: []
Input: head = [1]
Output: [1]
[0, 100]
の範囲内です. 0 <= Node.val <= 100
解题
方法一
思路
非递归
代码
public ListNode swapPairs(ListNode head) {
ListNode dummy = new ListNode(0);
dummy.next = head;
ListNode current = dummy;
while (current.next != null && current.next.next != null) {
ListNode first = current.next;
ListNode second = current.next.next;
first.next = second.next;
current.next = second;
current.next.next = first;
current = current.next.next;
}
return dummy.next;
}
复杂度分析
public ListNode swapPairs(ListNode head) {
ListNode dummy = new ListNode(0);
dummy.next = head;
ListNode current = dummy;
while (current.next != null && current.next.next != null) {
ListNode first = current.next;
ListNode second = current.next.next;
first.next = second.next;
current.next = second;
current.next.next = first;
current = current.next.next;
}
return dummy.next;
}
方法二
思路
グラフを描く
実装
以下のようなグラフを描く必要があります
代码
import java.util.*;
/**
* class LLNode {
* int val;
* LLNode next;
* }
*/
class Solution {
public LLNode solve(LLNode node) {
LLNode dummy = new LLNode();
LLNode prev = dummy, curr = node;
dummy.next = curr;
// d -> 1 -> 2 -> 3 (prev=d,curr=1)
while (curr != null && curr.next != null) {
// d -> 2
prev.next = curr.next;
// 1 -> 3
curr.next = curr.next.next;
// 2 -> 1
prev.next.next = curr;
// prev = 1 (d -> 2 -> 1 -> 3)
prev = prev.next.next;
// curr = 3 (d -> 2 -> 1 -> 3)
curr = curr.next;
}
return dummy.next;
}
}
复杂度分析
Reference
この問題について(ペアワイズ リンク リスト スワップ), 我々は、より多くの情報をここで見つけました https://dev.to/jiangwenqi/pairwise-linked-list-swap-5g36テキストは自由に共有またはコピーできます。ただし、このドキュメントのURLは参考URLとして残しておいてください。
Collection and Share based on the CC Protocol