兩兩交換鏈表中的節點
給定一個鏈表,兩兩交換其中相鄰的節點,並返回交換後的鏈表。
你不能只是單純的改變節點內部的值,而是需要實際的進行節點交換。
示例:
給定 1->2->3->4, 你應該返回 2->1->4->3.
思路
方法一:遞歸
算法:
從鏈表的頭節點 head 開始遞歸。
每次遞歸都負責交換一對節點。由 firstNode 和 secondNode 表示要交換的兩個節點。
下一次遞歸則是傳遞的是下一對需要交換的節點。若鏈表中還有節點,則繼續遞歸。
交換了兩個節點以後,返回 secondNode,因爲它是交換後的新頭。
在所有節點交換完成以後,我們返回交換後的頭,實際上是原始鏈表的第二個節點。
複雜度分析
- 時間複雜度:O(N)O(N),其中 NN 指的是鏈表的節點數量。
- 空間複雜度:O(N)O(N),遞歸過程使用的堆棧空間。
代碼
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
class Solution {
public ListNode swapPairs(ListNode head) {
if(head==null||head.next==null)
return head;
ListNode ans=head.next;
ListNode temp=swapPairs(head.next.next);
ans.next=head;
head.next=temp;
return ans;
}
}
方法二:迭代
我們把鏈表分爲兩部分,即奇數節點爲一部分,偶數節點爲一部分,A 指的是交換節點中的前面的節點,B 指的是要交換節點中的後面的節點。在完成它們的交換,我們還得用 prevNode 記錄 A 的前驅節點。
算法:
firstNode(即 A)
和secondNode(即 B)
分別遍歷偶數節點和奇數節點,即兩步看作一步。- 交換兩個節點:
firstNode.next = secondNode.next
secondNode.next = firstNode
3 還需要更新 prevNode.next
指向交換後的頭。
prevNode.next = secondNode
4 迭代完成後得到最終的交換結果。
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
class Solution {
public ListNode swapPairs(ListNode head) {
// Dummy node acts as the prevNode for the head node
// of the list and hence stores pointer to the head node.
ListNode dummy = new ListNode(-1);
dummy.next = head;
ListNode prevNode = dummy;
while ((head != null) && (head.next != null)) {
// Nodes to be swapped
ListNode firstNode = head;
ListNode secondNode = head.next;
// Swapping
prevNode.next = secondNode;
firstNode.next = secondNode.next;
secondNode.next = firstNode;
// Reinitializing the head and prevNode for next swap
prevNode = firstNode;
head = firstNode.next; // jump
}
// Return the new head node.
return dummy.next;
}
}
主方法
public class ListNode {
int val;
ListNode next = null;
ListNode(int val) {
this.val = val;
}
}
public static void main(String[] args) {
ListNode pHead = new ListNode(1);
ListNode pHead1 = new ListNode(2);
ListNode pHead2 = new ListNode(3);
ListNode pHead3 = new ListNode(4);
pHead.next = pHead1;
pHead1.next =pHead2;
pHead2.next =pHead3;
ListNode newpHead = swapPairs(pHead);
while (newpHead != null) {
System.out.println(newpHead.val);
newpHead = newpHead.next;
}
}