zoukankan      html  css  js  c++  java
  • 24. 两两交换链表中的节点

    <递归>

    题目


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

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

    示例:

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

     

    题解 - 迭代


    class Solution(object):
        def swapPairs(self, head):
            """
            :type head: ListNode
            :rtype: ListNode
            """ 
            pre = ListNode(-1)
            pre.next = head
            ret = pre
            while head and head.next:
                fst = pre.next
                sec = head.next
    
                pre.next = sec
                fst.next = sec.next
                sec.next = fst
    
                pre = fst
                head = fst.next
            return ret.next
    • 算法:

     

    题解 - 递归


     

     

     

  • 相关阅读:
    php utf-8
    thinkPHP--关于域名指向的问题
    PHP命名空间(Namespace)的使用详解
    thinkphp 动态配置
    枚举之称硬币
    5.7
    5.6
    5.5(OI一本通开始)
    5.4
    5.3
  • 原文地址:https://www.cnblogs.com/remly/p/11550921.html
Copyright © 2011-2022 走看看