Swap Nodes in Pairs
2016-09-09 09:55
183 查看
leetcode第24题,相邻链表两元素反转,这道题目标签虽然是easy,但是其实还是挺难的。
注意,这里要求在常量空间复杂度内完成,因此就不要想着找个列表记录下来在结成类表这种思路了。
首先,要明白的是,这道题最难的地方就是如何在两组相邻链表建立指针关系,我借鉴了一种非常巧妙的思路,那就是在每一组相邻元素的前面设置一个哑变量,这样利用这个哑变量就可以控制这一组相邻元素翻转而不影响其它元素。
# Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution(object):
def swapPairs(self, head):
"""
:type head: ListNode
:rtype: ListNode
"""
dum = ListNode(0)
dum.next = head
curr = dum
while curr.next and curr.next.next:
tmp = curr.next.next
curr.next.next = tmp.next
tmp.next = curr.next
curr.next = tmp
curr = curr.next.next
return dum.next
注意,这里要求在常量空间复杂度内完成,因此就不要想着找个列表记录下来在结成类表这种思路了。
首先,要明白的是,这道题最难的地方就是如何在两组相邻链表建立指针关系,我借鉴了一种非常巧妙的思路,那就是在每一组相邻元素的前面设置一个哑变量,这样利用这个哑变量就可以控制这一组相邻元素翻转而不影响其它元素。
# Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution(object):
def swapPairs(self, head):
"""
:type head: ListNode
:rtype: ListNode
"""
dum = ListNode(0)
dum.next = head
curr = dum
while curr.next and curr.next.next:
tmp = curr.next.next
curr.next.next = tmp.next
tmp.next = curr.next
curr.next = tmp
curr = curr.next.next
return dum.next
相关文章推荐
- [leetcode 24]Swap Nodes in Pairs-----成对翻转链表中的节点
- Swap Nodes in Pairs
- [LeetCode]Swap Nodes in Pairs
- LeetCode Algorithms #24 <Swap Nodes in Pairs>
- LeetCode 24 Swap Nodes in Pairs
- LeetCode题解——Swap Nodes in Pairs
- Swap Nodes in Pairs leetcode java
- 24. Swap Nodes in Pairs
- LeetCode#24 Swap Nodes in Pairs
- LeetCode之旅(21)-Swap Nodes in Pairs
- LeetCode#24 Swap Nodes in Pairs
- 【C++】【LeetCode】24. Swap Nodes in Pairs
- 24. Swap Nodes in Pairs
- LeetCode_Swap Nodes in Pairs
- Swap Nodes in Pairs
- LeetCode | Swap Nodes in Pairs
- Leetcode Swap Nodes in Pairs
- LeetCode Swap Nodes in Pairs
- 交换单链表中相邻的两个元素 Swap Nodes in Pairs
- leetcode Swap Nodes in Pairs