• 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)
    

      

    既然无论如何时间都会过去,为什么不选择做些有意义的事情呢
  • 相关阅读:
    微信小程序右上角胶囊的位置
    NLP复习大纲
    网站收藏
    css中如何调整插入背景图片的大小
    禁止Power Apps Canvas用户通过SharePoint Online UI界面访问站点list
    c++ vector基本知识
    c++ map基本知识
    c++ string操作
    python学习笔记30:操作excel
    c++, 如何run一个c++程序
  • 原文地址:https://www.cnblogs.com/xiaodongsuibi/p/8906577.html
Copyright © 2020-2023  润新知