24. Swap Nodes in Pairs [easy] (Python)
来源:互联网 发布:知乎女神芈十四真名 编辑:程序博客网 时间:2024/05/08 05:38
题目链接
https://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.
题目翻译
给定一个单链表,交换相邻的节点,并返回链表头。比如,给定1->2->3->4,你应该返回 2->1->4->3。
注意:你的算法应该是O(1)的空间复杂度,不能修改链表节点的值(val),只能修改节点。
思路方法
思路一
既然每次交换相邻节点,那么就以两个节点为一个单位做处理,循环每次交换两个相邻节点即可。
代码
# Definition for singly-linked list.# class ListNode(object):# def __init__(self, x):# self.val = x# self.next = Noneclass Solution(object): def swapPairs(self, head): """ :type head: ListNode :rtype: ListNode """ if not head or not head.next: return head pre = new_head = ListNode(0) while head and head.next: tmp = head.next head.next = tmp.next tmp.next = head pre.next = tmp pre = head head = head.next return new_head.next
说明
上面的思路,可以换个角度考虑:现在是用现在的节点构造一个新的链表,每次向新链表添加两个节点,这两个节点是原链表的相邻节点的逆序。
思路二
代码
# Definition for singly-linked list.# class ListNode(object):# def __init__(self, x):# self.val = x# self.next = Noneclass Solution(object): def swapPairs(self, head): """ :type head: ListNode :rtype: ListNode """ if not head or not head.next: return head new_head = head.next head.next = self.swapPairs(head.next.next) new_head.next = head return new_head
PS: 新手刷LeetCode,新手写博客,写错了或者写的不清楚还请帮忙指出,谢谢!
转载请注明:http://blog.csdn.net/coder_orz/article/details/51532184
0 0
- 24. Swap Nodes in Pairs [easy] (Python)
- 24. Swap Nodes in Pairs [easy]
- 24. Swap Nodes in Pairs Leetcode Python
- 24. Swap Nodes in Pairs(python)
- [leetcode: Python]24. Swap Nodes in Pairs
- 24.LeetCode Swap Nodes in Pairs(easy)[单链表]
- Leetcode 24. Swap Nodes in Pairs (Easy) (cpp)
- Swap Nodes in Pairs(easy)
- Swap Nodes in Pairs (EASY)
- Easy 24题 Swap Nodes in Pairs
- 24. Swap Nodes in Pairs
- 24. Swap Nodes in Pairs
- 24.Swap Nodes in Pairs
- 24. Swap Nodes in Pairs
- 24. Swap Nodes in Pairs
- 24. Swap Nodes in Pairs
- 24. Swap Nodes in Pairs
- 24. Swap Nodes in Pairs
- 006 Android应用开发的9个组件
- 利用搜索引擎来搜索特定网站中的关键词
- ReactNative(六)——利用RN状态机管理组件状态
- Masonry详解
- C++基础<02>—变量和基本类型
- 24. Swap Nodes in Pairs [easy] (Python)
- 中国计算机学会推荐投稿期刊和学术会议截稿汇总 - 五月版
- PAT (Advanced Level) Practise 1003. Emergency (25) Dijstra扩展应用
- linux echo 用法
- iOS 网络篇1—网络编程基础
- 9.Tornado的核心web框架tornado.web小结---RequestHandler和Application
- 数字电路的模拟
- 视频编码与封装
- JQuery中的元素选择器