自学内容网 自学内容网

leetcode链表(二)-两两交换链表中的节点

题目

. - 力扣(LeetCode)
给你一个链表,两两交换其中相邻的节点,并返回交换后链表的头节点。你必须在不修改节点内部的值的情况下完成本题(即,只能进行节点交换)。

思路

一定要使用虚拟头节点,将虚拟头节点的下个节点指向head

两两交换即使cur的下个节点指向2,再由2指向1,再由1指向3

那就

直接将1暂定义为temp1,2定义为temp2,3定义为temp3 

cur.next指向temp2,cur.next.next指向temp1,cur.next.next.next指向temp3

再将cur指向到最新的节点即可

代码

# 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]:
        if not head:
            return 
        phead= ListNode()
        phead.next = head
        cur = phead
        while cur.next and cur.next.next:
            temp1 = cur.next
            temp2 = cur.next.next
            temp3 = cur.next.next.next
            cur.next = temp2
            cur.next.next = temp1
            cur.next.next.next = temp3
            cur = cur.next.next
        return phead.next #最后返回一定要返回虚拟节点的下一个节点,即头节点,否则返回结果将缺少头节点


原文地址:https://blog.csdn.net/weixin_40198632/article/details/142861175

免责声明:本站文章内容转载自网络资源,如本站内容侵犯了原著者的合法权益,可联系本站删除。更多内容请关注自学内容网(zxcms.com)!