[链表]两两交换链表中的节点

两两交换链表中的节点

注意,这里是交换链表的物理节点。而不是交换它的数值。如果链表的节点个数为奇数,则最后一个节点不需要处理。

让我们在操作三四两个节点的时候,要将指针指向三的前一个节点。

cpp 复制代码
首先定义一个虚拟头节点。虚拟头节点的next指向真正的头节点。
dummyhead->next = head
cur = dummyhead
cur先指向dummyhead才能操作头节点和下一个节点。

接下来就是一个遍历的过程。当这个链表的节点数量为偶数的时候,cur.next空结束循环;当链表节点为奇数的时候,cur.next.next空结束循环.

while(cur->next != null && cur->next->next != null )  {

    如果把这两个条件反过来,容易发生空指针异常。因为先写后一个条件时,cur->next可能为空。
    cur指向dummyhead,是我们新new的一个节点,不可能为空
    dummyhead指向2,2指向1,1指向3

    我们在将dummyhead指向节点二之前。要将节点一的指针保存,否则没有办法表示节点1。也没有办法对节   点1进行操作;同时在我们进行节点二的赋值操作之前,对节点三也要进行保存否则,节点三也没有办法表示

    temp = cur->next   保存了节点1
    temp1 = cur->next->next->next   保存了节点3
    cur->next = cur->next->next
    cur->next->next = temp 
    temp->next = temp1 

    接下来我们要移动cur指针
    cur = cur->next->next

return dummyhead->next

python代码

python 复制代码
# 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: Optional[ListNode]) -> Optional[ListNode]:
        dummyhead =  ListNode()
        dummyhead.next = head
        cur = dummyhead
        while cur.next and cur.next.next :
            temp = cur.next
            # 1
            temp1 = cur.next.next.next
            # 3
            cur.next = cur.next.next
            # dummy-2
            cur.next.next = temp
            # 2-1
            temp.next =  temp1
            # 1-3
            cur = cur.next.next
            # cur->1
        return dummyhead.next
相关推荐
岁忧27 分钟前
(LeetCode 面试经典 150 题) 82. 删除排序链表中的重复元素 II (链表)
java·c++·leetcode·链表·面试·go
秋难降1 小时前
【数据结构与算法】———回溯之美
数据结构·算法
ikkkkkkkl1 小时前
LeetCode:347.前K个高频元素
数据结构·c++·算法·leetcode
_祝你今天愉快1 小时前
SparseArray & ArrayMap
android·数据结构
筱砚.1 小时前
【数据结构——并查集】
数据结构·算法
发发发发8882 小时前
leetcode 674.最长连续递增序列
java·数据结构·算法·leetcode·动态规划·最长连续递增序列
效效超爱笑3 小时前
单链表应用实践
数据结构·c++·链表
啊阿狸不会拉杆4 小时前
《算法导论》第 10 章 - 基本数据结构
数据结构·c++·b树·算法·链表·排序算法
_Chipen5 小时前
3363. 最多可收集的水果数目
数据结构·算法