题目:
给定一个链表,两两交换其中相邻的节点,并返回交换后的链表。
示例:
给定 1->2->3->4, 你应该返回 2->1->4->3.
说明:
你的算法只能使用常数的额外空间。
你不能只是单纯的改变节点内部的值,而是需要实际的进行节点交换。
解法思路还是先把Nodes导为list,然后可以通过索引更方便的两两互换,参考代码如下:
class Solution:
def swapPairs(self, head):
"""
:type head: ListNode
:rtype: ListNode
"""
if head is None:
return None
if head.next is None:
return head
temp = []
while head is not None:
temp.append(head.val)
head = head.next
i = 0
while i + 1 < len(temp):
t = temp[i]
temp[i] = temp[i + 1]
temp[i + 1] = t
i = i + 2
h = ListNode(temp[0])
c = ListNode(temp[1])
h.next = c
for j in range(2,len(temp)):
node = ListNode(temp[j])
c.next = node
c = c.next
return h
其它题目:leetcode题目答案讲解汇总(Python版 持续更新)
ps:如果您有好的建议,欢迎交流 :-D,
也欢迎访问我的个人博客 苔原带 (www.tundrazone.com)