電商模板免費(fèi)下載/資源企業(yè)網(wǎng)站排名優(yōu)化價格
兩兩交換鏈表中的節(jié)點(diǎn)【LC24】
給你一個鏈表,兩兩交換其中相鄰的節(jié)點(diǎn),并返回交換后鏈表的頭節(jié)點(diǎn)。你必須在不修改節(jié)點(diǎn)內(nèi)部的值的情況下完成本題(即,只能進(jìn)行節(jié)點(diǎn)交換)。
周賽暫停一周啦
-
思路:模擬
記錄前驅(qū)節(jié)點(diǎn),如果接下來還有兩個不為空的節(jié)點(diǎn)時,將其交換。
- 2022/4/15
- 2023/8/6
/*** Definition for singly-linked list.* public class ListNode {* int val;* ListNode next;* ListNode() {}* ListNode(int val) { this.val = val; }* ListNode(int val, ListNode next) { this.val = val; this.next = next; }* }*/ class Solution {public ListNode swapPairs(ListNode head) {ListNode dummyNode = new ListNode(-1,head);ListNode pre = dummyNode;ListNode cur = pre.next;while(pre != null && cur !=null && cur.next != null){ListNode tmp = cur.next.next;pre.next = cur.next;cur.next.next = cur;cur.next = tmp;pre = cur;cur = cur.next;}return dummyNode.next; } }
-
實(shí)現(xiàn):直接從前驅(qū)節(jié)點(diǎn)出發(fā)
2022/09/21 class Solution {public ListNode swapPairs(ListNode head) {ListNode dummyHead = new ListNode(0,head);ListNode node = dummyHead;while (node.next != null && node.next.next != null){ListNode nn = node.next.next;node.next.next = nn.next;nn.next = node.next;node.next = nn;node = node.next.next;}return dummyHead.next;} }
- 復(fù)雜度
- 時間復(fù)雜度: O ( n ) \mathcal{O}(n) O(n)
- 空間復(fù)雜度: O ( 1 ) \mathcal{O}(1) O(1)
- 復(fù)雜度
-
遞歸
class Solution {public ListNode swapPairs(ListNode head) {if (head == null || head.next == null) {return head;}ListNode newHead = head.next;head.next = swapPairs(newHead.next);newHead.next = head;return newHead;} }作者:LeetCode-Solution 鏈接:https://leetcode-cn.com/problems/swap-nodes-in-pairs/solution/liang-liang-jiao-huan-lian-biao-zhong-de-jie-di-91/ 來源:力扣(LeetCode) 著作權(quán)歸作者所有。商業(yè)轉(zhuǎn)載請聯(lián)系作者獲得授權(quán),非商業(yè)轉(zhuǎn)載請注明出處。
- 復(fù)雜度
- 時間復(fù)雜度: O ( n ) \mathcal{O}(n) O(n)
- 空間復(fù)雜度: O ( n ) \mathcal{O}(n) O(n)
- 復(fù)雜度