• 博客园logo
  • 会员
  • 众包
  • 新闻
  • 博问
  • 闪存
  • 赞助商
  • HarmonyOS
  • Chat2DB
    • 搜索
      所有博客
    • 搜索
      当前博客
  • 写随笔 我的博客 短消息 简洁模式
    用户头像
    我的博客 我的园子 账号设置 会员中心 简洁模式 ... 退出登录
    注册 登录

nunca

但行好事 莫问前程
  • 博客园
  • 联系
  • 订阅
  • 管理

公告

View Post

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)

  

既然无论如何时间都会过去,为什么不选择做些有意义的事情呢

posted on 2018-04-22 13:01  乐晓东随笔  阅读(145)  评论(0)    收藏  举报

刷新页面返回顶部
 
博客园  ©  2004-2025
浙公网安备 33010602011771号 浙ICP备2021040463号-3