zoukankan      html  css  js  c++  java
  • 【Leetcode链表】两两交换链表中的节点(24)

    题目

    给定一个链表,两两交换其中相邻的节点,并返回交换后的链表。你不能只是单纯的改变节点内部的值,而是需要实际的进行节点交换。

    示例:

    给定 1->2->3->4, 你应该返回 2->1->4->3.
    

    解答

    先在链表头开辟一个新节点thead并连接,赋值给一个新变量t,接下来由t在链表中改变节点指向,thead保持不变最后返回,当接下来有连续2个节点时开始交换指向,因为是两两交换,所以每次交换完成后,t往后走两步。

    思路图如下:

    通过代码如下:时间复杂度O(n)、空间复杂度O(1)

    # 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:
            thead = ListNode(0)
            thead.next = head
            t = thead
            while t.next and t.next.next:
                a, b = t.next, t.next.next
                t.next, a.next, b.next = b, b.next, a
                t = t.next.next
            return thead.next
    
    ## 注释
    # class Solution:
    #     def swapPairs(self, head: ListNode) -> ListNode:
    #         thead = ListNode(0)
    #         thead.next = head
    #         t = thead  # thead留在首部,返回时使用
    #         while t.next and t.next.next:  # 有两个数才交换
    #             a, b = t.next, t.next.next
    #             t.next, a.next, b.next = b, b.next, a  # t先断a,a断b,b再接a
    #             t = t.next.next  # 往后走两步,准备下两个数交换
    #         return thead.next
    
  • 相关阅读:
    OTA JAR和JAD的mime不同
    document.getElementById('selCatalog').remove(i)突然无效???!
    判断WAP1.1和WAP2.0并解析为wml或xhtml
    IE和firefox下显示html内容
    unixrisk tip
    unixftp windows
    unixstdin/stdout/stderr
    峰鸟摄影
    linuxgrep commond
    unixtutorial(recommended)
  • 原文地址:https://www.cnblogs.com/ldy-miss/p/11924154.html
Copyright © 2011-2022 走看看