zoukankan      html  css  js  c++  java
  • LeetCode Medium:24. Swap Nodes in Pairs

    一、题目

    Given a linked list, swap every two adjacent nodes and return its head.

    Example:

    Given 1->2->3->4, you should return the list as 2->1->4->3.

    Note:

    • Your algorithm should use only constant extra space.
    • You may not modify the values in the list's nodes, only nodes itself may be changed.

    意思就是给定一个链表,反转相邻的两个结点。

    二、思路

    定义一个head

    三、代码

    #coding:utf-8
    class ListNode:
        def __init__(self, x):
            self.val = x
            self.next = None
    
    class Solution:
        def swapPairs(self, head):
            """
            :type head: ListNode
            :rtype: ListNode
            """
            p = ListNode(0)
            p.next = head
            head = p
            while p.next != None and p.next.next != None:
                s = p.next.next
                p.next.next = s.next
                s.next = p.next
                p.next = s
                p = s.next
            print("after:",head.next.val,head.next.next.val,head.next.next.next.val,head.next.next.next.next.val)
            return head.next
    
    """
    idx = ListNode(3)
    n = idx
    n.next = ListNode(4)
    n = n.next
    n.next = ListNode(5)
    n = n.next
    return idx
    
    你将得到的结果是 3 -> 4 -> 5
    """
    if __name__ == '__main__':
        idx = ListNode(3)
        n = idx
        n.next = ListNode(4)
        n = n.next
        n.next = ListNode(5)
        n = n.next
        n.next = ListNode(6)
        n = n.next
        print("before:",idx.val,idx.next.val,idx.next.next.val,idx.next.next.next.val)
        ss = Solution()
        ss.swapPairs(idx)
    

      

    既然无论如何时间都会过去,为什么不选择做些有意义的事情呢
  • 相关阅读:
    基本的Dos命令
    OneCloud记录
    Wireguard笔记
    windows网络流量监控
    CoreDNS笔记
    Goland 使用[临时]
    js for循环的同步代码
    看我如何用微信上线CobaltStrike
    图数据库 Nebula Graph 在 Boss 直聘的应用
    熵池 在计算机科学与金融学中的应用
  • 原文地址:https://www.cnblogs.com/xiaodongsuibi/p/8906577.html
Copyright © 2011-2022 走看看