zoukankan      html  css  js  c++  java
  • 力扣—— Swap Nodes in Pairs(两两交换链表中的节点) python实现

    题目描述:

    中文:

    给定一个链表,两两交换其中相邻的节点,并返回交换后的链表。

    你不能只是单纯的改变节点内部的值,而是需要实际的进行节点交换。

    示例:

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

    英文:

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

    You may not modify the values in the list's nodes, only nodes itself may be changed.

    Example:

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

    # Definition for singly-linked list.
    # class ListNode(object):
    #     def __init__(self, x):
    #         self.val = x
    #         self.next = None
    
    class Solution(object):
        def swapPairs(self, head):
            """
            :type head: ListNode
            :rtype: ListNode
            """
            if head is None or head.next is None: 
                return head
    
            dummyhead = ListNode(0)
            dummyhead.next = head
    
            pre = dummyhead
            curr = head
            while curr is not None and curr.next is not None:
                tmp = curr.next
                curr.next = tmp.next
                tmp.next = pre.next 
                pre.next = tmp
                pre = curr
                curr = curr.next
            return dummyhead.next

    题目来源:力扣

  • 相关阅读:
    2-SAT
    模板 两次dfs
    SG函数与SG定理
    NIM博弈
    python 给小孩起名
    pytest 数据驱动
    pytest 结合selenium 运用案例
    字符串的转换方法与分割
    字符串的方法
    字符串常量池与字符串之间的比较
  • 原文地址:https://www.cnblogs.com/spp666/p/11651009.html
Copyright © 2011-2022 走看看