24. Swap Nodes in Pairs
2017-01-11 12:53
260 查看
题意: 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.
思路:这里有一点特别要说,python没有指针这个概念,所以这个头指针实际上就是第一个结点的一个成员变量,所以我在头结点之前,再建立一个结点,用于结点的交换,附代码:
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.
思路:这里有一点特别要说,python没有指针这个概念,所以这个头指针实际上就是第一个结点的一个成员变量,所以我在头结点之前,再建立一个结点,用于结点的交换,附代码:
def swapPairs(self, head): h = ListNode(0) h.next, p, f = head, head, h while p and p.next: q = p.next f.next = q p.next = q.next q.next = p f = p p = p.next return h.next
相关文章推荐
- LeetCode - 24. Swap Nodes in Pairs
- Leetcode||24.Swap Nodes in Pairs
- leetcode_24_Swap Nodes in Pairs
- [LeetCode]24.Swap Nodes in Pairs
- 24. Swap Nodes in Pairs
- 24. Swap Nodes in Pairs
- [Leetcode]24. Swap Nodes in Pairs
- LeetCode 24 Swap Nodes in Pairs
- [leetcode] 24. Swap Nodes in Pairs
- LinkedList-24-Swap Nodes in Pairs
- LeetCode(24) Swap Nodes in Pairs
- leetcode 24 Swap Nodes in Pairs
- LeetCode-24.Swap Nodes in Pairs
- Lettcode_24_Swap Nodes in Pairs
- leetcode24:Swap Nodes in Pairs
- [LeetCode]--24. Swap Nodes in Pairs
- LeetCode代码记录 24 Swap Nodes in Pairs
- 24. Swap Nodes in Pairs
- Leetcode: 24. Swap Nodes in Pairs
- [LeetCode-Algorithms-24] "Swap Nodes in Pairs" (2017.11.7-WEEK10)