leetcode-pp / 91alg-8-daily-check

5 stars 0 forks source link

【Day 8 】2022-07-22 - 24. 两两交换链表中的节点 #22

Closed azl397985856 closed 2 years ago

azl397985856 commented 2 years ago

24. 两两交换链表中的节点

入选理由

暂无

题目地址

https://leetcode-cn.com/problems/swap-nodes-in-pairs/

前置知识

你不能只是单纯的改变节点内部的值,而是需要实际的进行节点交换。

 

示例 1:


![image](https://assets.leetcode.com/uploads/2020/10/03/swap_ex1.jpg)

输入:head = [1,2,3,4] 输出:[2,1,4,3] 示例 2:

输入:head = [] 输出:[] 示例 3:

输入:head = [1] 输出:[1]  

提示:

链表中节点的数目在范围 [0, 100] 内 0 <= Node.val <= 100

Tomtao626 commented 2 years ago

思路

  • 递归

代码

func swapPairs(head *ListNode) *ListNode {
    if head == nil || head.Next == nil {
        return head
    }
    newHead := head.Next
    head.Next = swapPairs(newHead.Next)
    newHead.Next = head
    return newHead
}

复杂度

  • 时间 O(n)
  • 空间 O(n)
zhongranHerz commented 2 years ago

递归法(关注思想)

关注最小子结构,即将两个节点进行逆转。 将逆转后的尾节点.next 指向下一次递归的返回值 返回逆转后的链表头节点(ps:逆转前的第二个节点)

# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, x):
#         self.val = x
#         self.next = None

class Solution:
    def swapPairs(self, head: ListNode) -> ListNode:
        if head == None or head.next == None:
            return head

        l1 = head.next
        head.next = self.swapPairs(head.next.next)
        l1.next = head

        return l1
hydelovegood commented 2 years ago

思路

使用虚拟头节点,递归进行

代码

class Solution:
    def swapPairs(self, head: ListNode) -> ListNode:
        thead = ListNode(-1)
        thead.next = head
        c = thead
        while c.next and c.next.next:
            a, b=c.next, c.next.next
            c.next, a.next = b, b.next
            b.next = a
            c = c.next.next
        return thead.next

复杂度分析

时间复杂度On 空间复杂度O1

duke-github commented 2 years ago

思路

两两交换位置 

复杂度

时间复杂度 O(n) 空间复杂度O(1)

代码

class Solution {
    public ListNode swapPairs(ListNode head) {
        if (head == null || head.next == null) {
            return head;
        }
        ListNode ans = new ListNode(0, head);
        ListNode temp = ans;
        while (head != null && head.next != null) {
            //头指针指向2
            ans.next = ans.next.next;
            //1指向3
            head.next= head.next.next;
            //2指向1
            ans.next.next = head;
            //头指针再后移一位
            head = head.next;
            //临时指针后移两位
            ans= ans.next.next;
        }
        return temp.next;
    }
}
ShawYuan97 commented 2 years ago

代码

Python3 Code:


# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, val=0, next=None):
#         self.val = val
#         self.next = next
class Solution:
    def swapPairs(self, head: ListNode) -> ListNode:
        if not head or not head.next:
            return head
        dummy_head = ListNode()
        prev = dummy_head
        while head and head.next:
            first = head
            second = first.next

            prev.next = second
            first.next = second.next
            second.next = first
            prev = first

            head = first.next
        return dummy_head.next
pyxyzc commented 2 years ago

Idea

// preA -> A -> B -> nextB
// preA -> B -> A -> nextB 

创建虚拟头节点,以避免判断边界条件。

Code

class Solution
{
public:
    ListNode *swapPairs(ListNode *head)
    {
        if (head == nullptr || head->next == nullptr)
        {
            return head;
        }
        ListNode *dummy = new ListNode(-1, head);
        ListNode *pre = dummy;
        ListNode *cur = pre->next;
        while (cur != nullptr && cur->next != nullptr)
        {
            // pre->cur->(cur->next)->(cur->next->next)
            // pre->(cur->next)->cur->(cur->next->next)
            // cur指向(cur->next->next)
            ListNode *next = cur->next;
            cur->next = next->next;

            // (cur->next)指向cur
            next->next = cur;

            // pre指向cur->next
            pre->next = next;

            // 更新
            pre = cur;
            cur = cur->next;
        }
        return dummy->next;
    }
};

Complexity

miss1 commented 2 years ago
/**
 * @param {ListNode} head
 * @return {ListNode}
 * time: O(n)
 * space: O(1)
 * 定义一个pre节点和next节点,位置分别在要交换的两个节点的前后
 * 遍历交换节点
 */
var swapPairs = function(head) {
  if (head === null || head.next === null) return head;
  let res = new ListNode(0);
  let p1 = head;
  let p2 = head.next;
  let pre = res;
  pre.next = head;
  while (p1 && p2) {
    let next = p2.next;
    p1.next = next;
    p2.next = p1;
    pre.next = p2;
    pre = p1;
    p1 = next;
    p2 = p1 === null ? null : p1.next;
  }
  return res.next;
};
zzzkaiNS commented 2 years ago

思路

链表模拟题,可以先比划比划该怎么反转

代码

class Solution {
public:
    ListNode* swapPairs(ListNode* head) {
        if (!head || !head->next) return head;
        ListNode* dummy = new ListNode;
        dummy->next = head;
        ListNode* pre = dummy;
        while (pre->next && pre->next->next) {
            ListNode* cur = pre->next, * t = cur->next;
            pre->next = t;
            cur->next = t->next;
            t->next = cur;
            pre = cur;
        }
        return dummy->next;
    }
};
Erikahuang commented 2 years ago

思路

  • pre, cur, post三个节点进行操作,每次交换后pre后移至post节点继续交换。

代码

# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, val=0, next=None):
#         self.val = val
#         self.next = next
class Solution:
    def swapPairs(self, head: ListNode) -> ListNode:
        dummy_head = ListNode(next = head)
        pre = dummy_head

        while pre.next and pre.next.next:
            cur = pre.next
            post = pre.next.next

            pre.next = post
            cur.next = post.next
            post.next = cur

            pre = pre.next.next
        return dummy_head.next

复杂度

  • 时间复杂度: O(n)
  • 空间复杂度:O(1)
fan-svg commented 2 years ago

思路

因为本题中操作的最小单元就是两个相邻节点位置交换,所有采用递归的方法去重复的做这件事即可。
首先采用递归,就要确定返回值以及终止条件,在本题目中返回值就是交换过后的子链表的头节点,终止条件为当前节点为空或者下一节点为空(ps:最后一个节点)

代码

class Solution {
public:
    ListNode* swapPairs(ListNode* head) {
        if(head == NULL || head->next == NULL)
            return head;
        ListNode* n1 = head->next;
        head->next = swapPairs(n1->next);
        n1->next = head;
        return n1;
    }
};

复杂度分析

时间复杂度:O(n)
空间复杂度:O(1)

leungogogo commented 2 years ago
class Solution {
    public ListNode swapPairs(ListNode head) {
        ListNode dummy = new ListNode(), prev = dummy;
        dummy.next = head;
        while (prev != null) {
            ListNode cur = null, next = null;

            cur = prev.next;
            if (cur != null) {
                next = cur.next;
            }

            if (next != null) {
                prev.next = next;
                ListNode tmp = next.next;
                next.next = cur;
                cur.next = tmp;
            }
            prev = cur;
        }

        return dummy.next;
    }
}

Time: O(n)

Space: O(1)

MaylingLin commented 2 years ago

思路

迭代的方法,由preA -> A -> B ->BNext 修改为 preA ->B ->A ->nextB,交换两个节点位置,经过3次操作A.next = next.B; B.next = A; preA.next = B.

代码

class Solution:
    def swapPairs(self, head: ListNode) -> ListNode:
        if not head or not head.next: 
            return head
        ans = ListNode()
        ans.next = head.next
        pre = ans
        while head and head.next:
            next = head.next
            n_next = next.next

            next.next = head
            pre.next = next
            head.next = n_next

            pre = head
            head = n_next
        return ans.next

复杂度

nikojxie commented 2 years ago

思路

两两交换会涉及到4个节点,步骤拆解如下,同时new一个虚拟节点pre解决边界问题

初始:pre -> A -> B -> next

pre -> A -> next , B -> next

pre -> A -> next , B -> A

pre -> B -> A -> next

代码

function swapPairs(head) {
  if(!head || !head.next) return head
  let res = head.next
  let node = head
  let preNode = new ListNode()
  while(node && node.next) {
    let nNode = node.next
    let nnNode = nNode.next
    node.next = nnNode
    nNode.next = node
    preNode.next = nNode

    preNode = node
    node = nnNode
  }
  return res
}

复杂度

aiweng1981 commented 2 years ago

思路

  • 思路描述:今天先打卡,再慢慢琢磨,要加班了、

代码

#代码
if not head or not head.next: return head
    ans = ListNode()
    ans.next = head.next
    pre = ans
    while head and head.next:
        next = head.next
        n_next = next.next

        next.next = head
        pre.next = next
        head.next = n_next
        # 更新指针
        pre = head
        head = n_next
    return ans.next

复杂度

  • 时间复杂度: O(N)
  • 空间复杂度: O(1)
kiirii4 commented 2 years ago

思路

递归,原来的头节点是新链表第二个节点,第二个节点在新链表为头节点

代码

            class Solution {
public:
    ListNode* swapPairs(ListNode* head) {
        if(head == nullptr || head->next == nullptr) return head;
        ListNode* newHead = head->next;
        head->next = swapPairs(newHead->next);
        newHead->next = head;
        return newHead;
    }
};

复杂度分析

时间O(n) 空间O(n)

liuajingliu commented 2 years ago

解题思路

  1. 设置虚拟节点,定义pre指针,指向当前虚拟节点
  2. 当pre.next以及pre.next.next指针均不为空时,开始交换
  3. 令cur指针指向pre.next;next指针指向pre.next.next
  4. 交换过程如下:
    • pre.next = next
    • cur.next = next.next
    • next.next = cur
    • pre = cur

代码实现

javaScript

var swapPairs = function(head) {
    let dummyNode = new ListNode(0);
    dummyNode.next = head;
    let pre = dummyNode;
    while(pre.next && pre.next.next) {
        const cur = pre.next;
        const next = pre.next.next;
        pre.next = next;
        cur.next = next.next;
        next.next = cur;
        pre = cur;
    }
    return dummyNode.next;
};

复杂度分析

VictorHuang99 commented 2 years ago
CODE:

var swapPairs = function(head) {

    let dumpHead = new ListNode(0, head);
    let tmp = dumpHead;

    while(tmp.next && tmp.next.next) {
        let prev = tmp.next, cur = tmp.next.next.next;

        tmp.next = prev.next;
        prev.next.next = prev;
        prev.next = cur;

        tmp = tmp.next.next;
    }

    return dumpHead.next;

};
zhg1992 commented 2 years ago
//golang
/**
 * Definition for singly-linked list.
 * type ListNode struct {
 *     Val int
 *     Next *ListNode
 * }
 */
func swapPairs(head *ListNode) *ListNode {
  if head == nil || head.Next == nil {
    return head
  }
  newHead := head.Next
  head.Next = swapPairs(newHead.Next)
  newHead.Next = head
  return newHead
}
jackgaoyuan commented 2 years ago

func swapPairs(head ListNode) ListNode { if head == nil || head.Next == nil{ return head } cur, next := head, head.Next var pre *ListNode for i:=0;i<2;i++{ cur.Next = pre pre = cur cur = next if next != nil{ next = next.Next } } head.Next = swapPairs(cur) return pre }

PGquestions commented 2 years ago

思路

由于所有的两两交换逻辑都是一样的,因此我们只要关注某一个两两交换如何实现就可以了。

因为要修改的是二个一组的链表节点,所以需要操作 4 个节点。例如:将链表 A -> B 进行逆转,我们需要得到 A,B 以及 A 的前置节点 preA,以及 B 的后置节点 nextB

原始链表为 preA -> A -> B -> nextB,我们需要改为 preA -> B -> A -> nextB,接下来用同样的逻辑交换 nextB 以及 nextB 的下一个元素。

代码

Java Code:


/**
 * 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) {
        if (head == null || head.next == null) return head;
        ListNode preNode = new ListNode(-1, head);
        ListNode res;
        preNode.next = head;
        res = head.next;
        ListNode firstNode = head;
        ListNode secondNode;
        ListNode nextNode;
        while (firstNode != null && firstNode.next != null) {
            secondNode = firstNode.next;
            nextNode = secondNode.next;
            firstNode.next = nextNode;
            secondNode.next = firstNode;
            preNode.next = secondNode;
            preNode = firstNode;
            firstNode = nextNode;
        }
        return res;

    }
}

复杂度分析

令 n 为数组长度。

yibenxiao commented 2 years ago

【Day 8】24. 两两交换链表中的节点

代码

class Solution {
public:
    ListNode* swapPairs(ListNode* head) {
        if (head == NULL || head->next == NULL)
            return head;
        ListNode * p1 = head;
        ListNode * p2 = head->next;
        ListNode * ans = head->next; \
            ListNode *pre = NULL;
        while (1)
        {
            ListNode * tmp = p2->next;
            p2->next = p1;
            p1->next = tmp;
            if(pre)
                pre->next = p2;

            if (p1->next && p1->next->next)
            {
                pre = p1;
                p1 = p1->next;
                p2 = p1->next;
            }
            else break;
        }
        return ans;
    }
};

复杂度

时间复杂度:O(N)

空间复杂度:O(1)

SunL1GHT commented 2 years ago

思路

递归法交换两两节点,每次将当前头节点的下一个和下下个节点进行交换;

代码

class Solution {
    public ListNode swapPairs(ListNode head) {
        if (head == null || head.next == null)
            return head;

        ListNode subResult = swapPairs(head.next.next);
        ListNode headNext = head.next;
        headNext.next = head;
        head.next = subResult;
        return headNext;
    }
}

复杂度

Yuki-yzy commented 2 years ago

思路

定义虚头节点,进行交换

代码

var swapPairs = function(head) {
    let ret = new ListNode(0,head) 
    let temp = ret
    while(temp.next && temp.next.next) {
        let pre = temp.next
        let cur = pre.next
        pre.next = cur.next
        cur.next = pre
        temp.next = cur
        temp = pre
    }
    return ret.next
};

复杂度

时间:O(1)

空间:O(n)

ricjli commented 2 years ago

Simulation:

— 链表问题 - 只要不要吝啬用指针, 并且画图操作 就没有问题!!!

— In order to swap a pair of nodes in a linked list, we need to get 4 pointers. prev, a, b, after. After we got all the pointers, we just need to link them by the order.

class Solution {
    public ListNode swapPairs(ListNode head) {
        ListNode dummy = new ListNode(-1, head);
        ListNode ptr = dummy; 
        while(ptr.next != null && ptr.next.next != null){

            ListNode a = ptr.next;
            ListNode b = ptr.next.next;
            ListNode after = ptr.next.next.next; 
            ptr.next = b;
            b.next = a;
            a.next = after;

            ptr = ptr.next.next;
        }

        return dummy.next; 
    }
}

Complexity:

Time: O(n)

Space: O(1)

degndaixingqiu commented 2 years ago
public:
    ListNode* swapPairs(ListNode* head) {
        ListNode* dummyHead = new ListNode(0); 
        dummyHead->next = head;
        ListNode* cur = dummyHead;
        while(cur->next != nullptr && cur->next->next != nullptr) {
            ListNode* tmp = cur->next; 
            ListNode* tmp1 = cur->next->next->next; 

            cur->next = cur->next->next;   
            cur->next->next = tmp;          
            cur->next->next->next = tmp1;   

            cur = cur->next->next; 
        }
        return dummyHead->next;
    }
};
jerry-lllman commented 2 years ago

解题思路

本题重点在于需要借助一个虚拟头节点,来承载头指针的引用(头指针不会丢失) 交换思路与普通的交换没有太大区别

代码实现

function swapPairs(head: ListNode | null): ListNode | null {
  let dummyHead = new ListNode(0, head) // 需要一个虚拟头节点
  let temp = dummyHead
  while(temp.next && temp.next.next) { // 因为是两两交换,所以需要判断两个next
    const next1 = temp.next // 拿到第一个 next
    const next2 = temp.next.next // 拿到第二个 next
    temp.next = next2 // 将当前的 temp.next 指向 第二个 next         //// 也就是将  1 的 next 指向 3
    next1.next = next2.next // 再将 next1.next 指向 next2.next     //// 将 2 的 next 指向 4
    next2.next = next1 // 接着将 next2.next 指向为 next1            //// 再将 3 的 next 指向  2,至此完成交换
    temp = next1 // 完成交换,处理下一个节点
  }
    return dummyHead.next
};

复杂度分析

时间复杂度:O(n) 空间复杂度:O(1)

Cusanity commented 2 years ago

public class Solution { public ListNode swapPairs(ListNode head) { if (head == null || head.next == null) return head; ListNode second = head.next; ListNode third = second.next; second.next = head; head.next = swapPairs(third); return second; } }

Luckysq999 commented 2 years ago

思路

递归

代码

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;
    }
}

复杂度分析

LuckyRyan-web commented 2 years ago
/**
 * Definition for singly-linked list.
 * class ListNode {
 *     val: number
 *     next: ListNode | null
 *     constructor(val?: number, next?: ListNode | null) {
 *         this.val = (val===undefined ? 0 : val)
 *         this.next = (next===undefined ? null : next)
 *     }
 * }
 */

function swapPairs(head: ListNode | null): ListNode | null {
    if (!head || !head?.next) {
        return head
    }

    let preNode = new ListNode()

    preNode.next = head

    let p = preNode

    while (p?.next !== null && p?.next?.next !== null) {
        const node1 = p.next
        const node2 = p.next.next

        p.next = node2

        node1.next = node2.next

        node2.next = node1

        p = node1
    }

    return preNode.next
};
cyang258 commented 2 years ago
思路

we repeatedly swap two node, so we could use recursion to repeat the swap steps

public ListNode swapPairs(ListNode head) {
        if(head == null || head.next == null) return head;

        // Nodes to be swapped
        ListNode firstNode = head;
        ListNode secondNode = head.next;

        // Swap
        firstNode.next = swapPairs(secondNode.next);
        secondNode.next = firstNode;

        // Now the head is second node, so return it
        return secondNode;
}

Time Complexity: for each recursion the time complexity is O(1), and we run through the whole list nodes, thus it is O(N)

Space Complexity: we didn't use additional data structures, so it is O(1)

chenmengyu commented 2 years ago

代码

var swapPairs = function(head) {
    const dummyHead = new ListNode(0);
    dummyHead.next = head;
    let temp = dummyHead;
    while (temp.next !== null && temp.next.next !== null) {
        const node1 = temp.next;
        const node2 = temp.next.next;
        temp.next = node2;
        node1.next = node2.next;
        node2.next = node1;
        temp = node1;
    }
    return dummyHead.next;
};

复杂度

phoenixflyingsky commented 2 years ago

Idea

Use iterations to simulate the process

Code


/**
 * 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) {
        //corner case
        if(head == null || head.next == null) {
            return head;
        }

        ListNode dummy = new ListNode();
        dummy.next = head;

        ListNode pre = dummy;
        ListNode curr = dummy.next;
        ListNode next = curr.next;

        while(curr != null && next != null) {
            pre = swap(pre, next);
            curr = pre.next;
            if(curr != null) {
                next = curr.next;
            }
        }

        return dummy.next;
    }

    private ListNode swap(ListNode pre, ListNode next) {
        ListNode curr = pre.next;
        ListNode res = curr;

        ListNode temp = next.next;

        pre.next = next;
        next.next = curr;
        curr.next = temp;

        return res;
    }
}

Complexity Analysis

hx-code commented 2 years ago
var swapPairs = function(head) {
    let dummyNode = new ListNode(0,head);
    let now = dummyNode;
    while(now.next && now.next.next) {
        let second = now.next.next;
        let first = now.next;
        let next = second.next;
        now.next = second;
        second.next = first;
        first.next = next;
        now = now.next.next;
    }
    return dummyNode.next;
};
zzz607 commented 2 years ago

算法

递归

代码


func swapPairs(head *ListNode) *ListNode {
    // 1 -> 2 -> 3 -> 4
    // 1 -> 2 -> 3
    // 1 -> 2
    if head == nil || head.Next == nil {
        return head
    }

    p := head.Next
    head.Next = swapPairs(p.Next)
    p.Next = head
    return p
}

复杂度

Mryao1 commented 2 years ago
class Solution {
    public ListNode swapPairs(ListNode head) {
        ListNode dummy = new ListNode(0);
        dummy.next = head;
        for(ListNode p = dummy; p.next != null && p.next.next != null;)
        {
            ListNode a = p.next;    //虚拟头节点
            ListNode b = a.next;
            p.next = b;
            a.next = b.next;
            b.next = a;
            p = a;
        }
        return dummy.next;
    }
}
JohnxiZhao commented 2 years ago
class Solution {
    public ListNode swapPairs(ListNode head) {
        if(head == null || head.next == null){
            return head;
        }
        ListNode next = head.next;
        head.next = swapPairs(next.next);
        next.next = head;
        return next;
    }
}
wyz999 commented 2 years ago

思路

递归节点,亮亮交换

代码

golang

func swapPairs(head *ListNode) *ListNode {
    if head==nil||head.Next==nil{
        return head
    }
    nextNode := head.Next
    head.Next = swapPairs(nextNode.Next)
    nextNode.Next = head
    return nextNode

}

时空复杂度

xxiaomm commented 2 years ago

Link

https://leetcode.com/problems/swap-nodes-in-pairs/

Clarifications / Constraints

  1. number of nodes;

Idea_1

  1. Recursion;
  2. Store the recursion result with node ret;
  3. Swap the current pair;
  4. The tail point to the ret;
  5. return the new head;

Code

// recursion: O(n), O(n)
class Solution {
    public ListNode swapPairs(ListNode head) {
        if (head == null || head.next == null) return head;
        ListNode ret = swapPairs(head.next.next);
        ListNode nxt = head.next;
        head.next = ret;
        nxt.next = head;
        return nxt;

    }
} 

Complexity

Time complexity: O(n).
Space complexity: O(n).

Idea_2

  1. Iteration;
  2. Use the dummy node, because the head node changed;
  3. Store the next pair pointer and the prev pointer of the current pair;
  4. swap the current pair;

Code

// Iteration: O(n), O(1)
class Solution {
    public ListNode swapPairs(ListNode head) {
        ListNode dummy = new ListNode(-1, head);
        ListNode prev = dummy, curr = head, nxt = null;
        while (curr != null && curr.next != null) {
            nxt = curr.next.next;
            prev.next = curr.next;
            curr.next.next = curr;
            curr.next = nxt;
            prev = curr;
            curr = nxt;
        }
        return dummy.next;
    }
}

Complexity

Time complexity: O(n).
Space complexity: O(1).

jay-xzj commented 2 years ago

class Solution { public ListNode swapPairs(ListNode head) { ListNode dummyHead = new ListNode(0); dummyHead.next = head; ListNode temp = dummyHead; while (temp.next != null && temp.next.next != null) { ListNode node1 = temp.next; ListNode node2 = temp.next.next; temp.next = node2; node1.next = node2.next; node2.next = node1; temp = node1; } return dummyHead.next; } }

AtaraxyAdong commented 2 years ago

思路

链表的节点,两两互换位置,若是遇到长度为奇数的列表,最后一个节点不动。定义了四个变量,分别表示:上一个节点,当前节点、下一个节点和临时存储的值。两个节点为步长,遍历链表,交换两个节点的顺序,并把前一个节点的next赋值为交换后的第一个节点。直到链表结束即可

代码

class Solution {
    public ListNode swapPairs(ListNode head) {
        if (head == null || head.next == null) {
            return head;
        }
        ListNode pre = null;
        ListNode current = head;
        ListNode next = head.next;
        ListNode tmp;
        head = next;
        while (true) {
            tmp = next.next;
            current.next = tmp;
            next.next = current;
            if (pre != null) {
                pre.next = next;
            }

            pre = current;
            if (pre.next == null) {
                return head;
            }
            current = pre.next;
            if (pre.next.next == null) {
                return head;
            }
            next = pre.next.next;
        }
    }
}

复杂度分析

mhcn commented 2 years ago

/**

YANGZ001 commented 2 years ago

LeetCode Link

Swap Nodes in Pairs - LeetCode

Idea

Find every two listNode. And swap. Could be iteratively or recursively.

Code

/**
 * 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) {
        // Recursively
        if (head == null || head.next == null) return head;
        ListNode rest = swapPairs(head.next.next);
        ListNode a = head;
        ListNode b = head.next;
        b.next = a;
        a.next = rest;
        return b;
    }

    public ListNode swapPairs(ListNode head) {
        // Iteratively
        if (head == null || head.next == null) return head;
        ListNode dummy = new ListNode(0);
        dummy.next = head;
        ListNode p = dummy;
        while (p.next != null && p.next.next != null) {
            ListNode a = p.next;
            ListNode b = p.next.next;
            ListNode next = b.next;
            p.next = b;
            b.next = a;
            a.next = next;
            p = a;
        }
        return dummy.next;
    }
}

Complexity Analysis

Time Complexity: O(N)

Space Complexity: O(1)

zhangtuo1999 commented 2 years ago
function swapPairs(head: ListNode | null): ListNode | null {
  const dummy = new ListNode(0)
  let pre = dummy
  pre.next = head
  while (pre.next && pre.next.next) {
    let one = pre.next
    let two = one.next;
    [pre.next, one.next, two.next] = [two, two.next, one]
    pre = one
  }

  return dummy.next
};
yuzejia commented 2 years ago

思路

利用递归 来交换节点

代码

function swapPairs(head: ListNode | null): ListNode | null {

    if(head == null || head.next ===  null) {
        return head
    }

    // 2n
    let last = head.next;
    // last.next === 2n+1  
    // return 2n+2
    let next2 = swapPairs(last.next)
    // 2n = 2n+2
    head.next = next2
    // 2n = 2n+1
    last.next = head
    return last
};
findalyzhou commented 2 years ago

思路:递归交换节点


代码

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; 
    }

codingtrains commented 2 years ago

思路

使用指针复制,完成交换

代码

class Solution:
    def swapPairs(self, head):
        ret = ListNode()
        ret.next = head
        tmp = ret
        while tmp.next and tmp.next.next:
            t3 = tmp.next.next.next
            t2 = tmp.next
            tmp.next = tmp.next.next
            tmp.next.next = t2
            t2.next = t3
            tmp = t2
        return ret.next
yaya-bb commented 2 years ago

题目地址()

https://leetcode.cn/problems/swap-nodes-in-pairs/submissions/

题目描述

前置知识

公司

思路

关键点

代码

JS Code:

``

/**



**复杂度分析**

令 n 为数组长度。

- 时间复杂度:$O(n)$
- 空间复杂度:$O(1)$
ZhongXiangXiang commented 2 years ago

代码

 */
var swapPairs = function(head) {
    if (!head || !head.next) {
        return head
    }
    let pre = head.next
    let next = head
    let tmp = pre.next
    head = head.next
    while (next.next) {
        // pre=2指向next=1, next再指向tmp=3的next=4,
        // 然后重新赋值,新一轮重新指向
        // console.log(pre, next, tmp)
        pre.next = next
        next.next = tmp ? (tmp.next || tmp) : null
        if (tmp) {
            pre = tmp.next
            next = tmp
            tmp = pre ? pre.next : null
        }
    }
    return head
};

复杂度

时间:O(n) 空间:O(1)

kaiykk commented 2 years ago

思路

加一个dummy头,需要两个指针作为prev和cur,可以容易找头节点,因为最后返回肯定是要头节点的

class Solution:
    def swapPairs(self, head: ListNode) -> ListNode:
        if not head:
            return head
        dummy_node = ListNode(-1)
        dummy_node.next = head
        prev_node, cur_node = dummy_node, head
        while cur_node and cur_node.next:
            next_node = cur_node.next
            prev_node.next = next_node
            next_cur_node = next_node.next
            next_node.next = cur_node
            cur_node.next = next_cur_node
            prev_node, cur_node = cur_node, next_cur_node

        return dummy_node.next

复杂度

yingchehu commented 2 years ago
# 假設 Linked List 長這樣 A -> B -> C ->
# 如果要換 A, B,先讓 left, right 分別在這兩個位置上:left -> A -> B(right) -> C ->
# 執行 swap 以後再將 left, right 往下一個目標位置移動
class Solution:
    def swapPairs(self, head: Optional[ListNode]) -> Optional[ListNode]:
        if not head:
            return head
        if not head.next:
            return head

        left = ListNode()
        # left 從 head 前一個 node 開始
        left.next = head
        # right 從 head 下一個 node 開始
        right = head.next

        head = None
        while True:
            # swap nodes
            left.next.next = right.next
            right.next = left.next
            left.next = right
            # 第一輪的 swap 要指定新的 head
            if not head:
                head = right

            # 往右移動,如果節點不夠了就中止迴圈
            left = right.next
            if left.next and left.next.next:
                right = left.next.next
            else:
                break

        return head

# Time: O(N)
# Space: O(1)