給定一個鏈表,兩兩交換其中相鄰的節點,並返回交換後的鏈表。
你不能只是單純的改變節點內部的值,而是需要實際的進行節點交換。
示例:
給定 1->2->3->4, 你應該返回 2->1->4->3.
來源:力扣(LeetCode)
鏈接:https://leetcode-cn.com/problems/swap-nodes-in-pairs
著作權歸領釦網絡所有。商業轉載請聯繫官方授權,非商業轉載請註明出處。
class Solution {
public ListNode swapPairs(ListNode head) {
// return swapPairsI(head);
return swapPairsII(head);
}
//方法二:非遞歸
//1.定義first爲交換節點中前面的節點,second爲交換節點中後面的節點
//2.定義prevNode爲first的前驅節點
//3.交換兩個節點,同時更新head和prev節點
private ListNode swapPairsII(ListNode head) {
ListNode dummy = new ListNode(0);
dummy.next = head;
ListNode prev = dummy;
while (head != null && head.next != null) {
//定義兩個節點
ListNode first = head;
ListNode second = head.next;
//交換
prev.next = second;
first.next = second.next;
second.next = first;
//更新head和prev節點
prev = first;
head = first.next;
}
//返回新的頭結點
return dummy.next;
}
//方法一:遞歸
//遞歸本質就是不斷重複相同的事情,主要關注三點:
//1.終止條件
//2.調用單元做了什麼
//3.返回值
private ListNode swapPairsI(ListNode head) {
//終止條件
if (head == null || head.next == null) return head;
//調用單元 1-2-3-4轉換成2-1-4-3
ListNode first = head;
ListNode second = head.next;
//first連接交換完成的子鏈表
first.next = swapPairs(second.next);
//second連接first
second.next = first;
//返回子鏈表的頭結點
return second;
}
}