Table of Content
题目:
给定一个链表,两两交换其中相邻的节点,并返回交换后的链表。示例:给定 1->2->3->4, 你应该返回 2->1->4->3.说明:你的算法只能使用常数的额外空间。你不能只是单纯的改变节点内部的值,而是需要实际的进行节点交换。
解法思路还是先把Nodes导为list,然后可以通过索引更方便的两两互换,参考代码如下,beats 98%:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 |
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 |
如果您有好的建议,欢迎来信与我交流

也欢迎关注微信公众号“苔原带”

