LeetCode——Swap Nodes in Pairs
1329 ワード
Given a linked list, swap every two adjacent nodes and return its head.
For example, Given
Your algorithm should use only constant space. You may not modify the values in the list, only nodes itself can be changed. 原題リンク:https://oj.leetcode.com/problems/swap-nodes-in-pairs/
タイトル:チェーンテーブルを1つ与え、隣接ノードを2つ交換して返します.
あなたのアルゴリズムは定数空間しか使用できません.テーブルの値は変更できません.ノード自体のみ変更できます.
考え方:まず、2つのノードの値を直接交換します.通過できますが、要求に合わないです.
2つ目の方法:仮想ヘッダノードを先に設定し、空にならないようにします.ノードの参照を再交換します.
For example, Given
1->2->3->4
, you should return the list as 2->1->4->3
. Your algorithm should use only constant space. You may not modify the values in the list, only nodes itself can be changed. 原題リンク:https://oj.leetcode.com/problems/swap-nodes-in-pairs/
タイトル:チェーンテーブルを1つ与え、隣接ノードを2つ交換して返します.
あなたのアルゴリズムは定数空間しか使用できません.テーブルの値は変更できません.ノード自体のみ変更できます.
考え方:まず、2つのノードの値を直接交換します.通過できますが、要求に合わないです.
public ListNode swapPairs(ListNode head) {
if (head == null || head.next == null)
return head;
ListNode back = head;
while (back != null) {
if (back.next != null) {
int val = back.val;
back.val = back.next.val;
back.next.val = val;
back = back.next.next;
} else
break;
}
return head;
}
2つ目の方法:仮想ヘッダノードを先に設定し、空にならないようにします.ノードの参照を再交換します.
public ListNode swapPairs(ListNode head) {
ListNode dummy = new ListNode(-1);
dummy.next = head;
ListNode pre = dummy;
while (head != null && head.next != null) {
ListNode tmp = head.next.next;
pre.next = head.next;
head.next.next = head;
head.next = tmp;
pre = head;
head = tmp;
}
return dummy.next;
}