LeetCode 24.兩兩交換連結串列中的節點
阿新 • • 發佈:2020-08-24
題目傳送門:兩兩交換連結串列中的節點
給定一個連結串列,兩兩交換其中相鄰的節點,並返回交換後的連結串列。
你不能只是單純的改變節點內部的值,而是需要實際的進行節點交換。
示例:
給定 1->2->3->4, 你應該返回 2->1->4->3.
遞迴法:
- 時間複雜度:O(N),其中 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) { //1.如果連結串列的長度小於2,則沒有可交換的元素,返回連結串列 if(head == null || head.next == null) return head; ListNode next = head.next; //2.使用遞迴的方法解決問題,因為是兩兩交換節點,所以引數為next.next head.next = swapPairs(next.next); //3.解決簡單問題 next.next=head; return next; } }
迭代法:
- 時間複雜度:O(N),其中 N 指的是連結串列的節點數量。
- 空間複雜度:O(1)。
/** * Definition for singly-linked list. * public class ListNode { * int val; * ListNode next; * ListNode(int x) { val = x; } * } */ class Solution { public ListNode swapPairs(ListNode head) { ListNode dummy = new ListNode(-1); dummy.next = head; ListNode pre = dummy; while((head != null)&&(head.next != null)) { //1.首先定義兩個點的位置 ListNode first = head; ListNode second = head.next; //進行交換操作 pre.next = second; first.next = second.next; second.next = first; //進行指標的移動 pre = first; head = first.next; } return dummy.next; } }