zoukankan      html  css  js  c++  java
  • [leetcode]Swap Nodes in Pairs @ Python

    原题地址:http://oj.leetcode.com/problems/swap-nodes-in-pairs/

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

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

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

    题意:将链表中的节点两两交换。Given 1->2->3->4, you should return the list as 2->1->4->3.

    解题思路:这题主要涉及到链表的基本操作。加一个头结点,操作起来会很方便。另外配了一个示意图 [本图是我asrman原创]

    代码:

    # Definition for singly-linked list.
    # class ListNode:
    #     def __init__(self, x):
    #         self.val = x
    #         self.next = None
    
    class Solution:
        # @param a ListNode
        # @return a ListNode
        def swapPairs(self, head):
            dummy = ListNode(0)
            dummy.next = head
            pre, curr = dummy, head
            while curr and curr.next:       # curr =1, curr.next =2
                pre.next = curr.next        # 0 --> 2
                curr.next = pre.next.next   # 1 --> 3  # curr.next.next
                pre.next.next = curr        # 2 --> 1
                pre, curr = curr,curr.next  # pre = 1, curr= 3
            return dummy.next

    参考:

    https://oj.leetcode.com/discuss/3608/seeking-for-a-better-solution

  • 相关阅读:
    elasticsearch之python操作
    Elasticsearch之性能优化
    Elasticsearch之基本使用
    Redis主从哨兵集群搭建
    Docker Swarm集群
    Elasticsearch之权限验证(Basic)
    docker之网络与数据管理
    docker之可视化工具
    基于Github gist的代码片段管理工具Lepton
    Redis工具之redis_rdb_tools
  • 原文地址:https://www.cnblogs.com/asrman/p/3972094.html
Copyright © 2011-2022 走看看