day04 代码随想录算法训练营 24. 两两交换链表中的节点

发布时间 2024-01-01 19:09:02作者: 山雨欲來風滿楼

题目:24. 两两交换链表中的节点

我的感悟:

  • 我感觉,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]:

        dummy_head = ListNode()
        dummy_head.next = head
        current = dummy_head
        
        # 必须有cur的下一个和下下个才能交换,否则说明已经交换结束了
        while current.next and current.next.next:
            temp = current.next # 防止节点修改
            temp1 = current.next.next.next
            
            current.next = current.next.next
            current.next.next = temp
            temp.next = temp1
            current = current.next.next
        return dummy_head.next

通过截图:

资料:

题目链接/文章讲解/视频讲解: https://programmercarl.com/0024.%E4%B8%A4%E4%B8%A4%E4%BA%A4%E6%8D%A2%E9%93%BE%E8%A1%A8%E4%B8%AD%E7%9A%84%E8%8A%82%E7%82%B9.html