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

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

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

    解题思路:这题主要涉及到链表的操作,没什么特别的技巧,注意不要出错就好。最好加一个头结点,操作起来会很方便。

    代码:

    # 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):
            if head == None or head.next == None:
                return head
            dummy = ListNode(0); dummy.next = head
            p = dummy
            while p.next and p.next.next:
                tmp = p.next.next
                p.next.next = tmp.next
                tmp.next = p.next
                p.next = tmp
                p = p.next.next
            return dummy.next
            
  • 相关阅读:
    排序规则
    revert
    添加字段modify
    修改字段名change
    修改字段注释modify
    修改字段类型modify
    file类型input框赋值
    disabled
    js失去焦点触发
    别把软件开发当做养家糊口的工具...
  • 原文地址:https://www.cnblogs.com/zuoyuan/p/3701919.html
Copyright © 2011-2022 走看看