LeetCode算法題python解法:24. Swap Nodes in Pairs
阿新 • • 發佈:2018-09-26
etc while bin pytho append pen usr and 特殊情況
原題:
Given a linked list, swap every two adjacent nodes and return its head.
Example:
Given1->2->3->4
, you should return the list as2->1->4->3
.
Note:
- Your algorithm should use only constant extra space.
- You may not modify the values in the list‘s nodes, only nodes itself may be changed.
中文翻譯:
給定鏈表,交換每兩個相鄰節點並返回其頭部。
例:
給定1->2->3->4
,您應該將列表作為2->1->4->3
。
註意:
- 您的算法應該只使用恒定的額外空間。
- 您可能無法修改列表節點中的值,只能更改節點本身。
解題思路:該題非常簡單,給定鏈表兩兩對調然後重新鏈接,返回新鏈表的頭部即可。將鏈表遍歷添加到一個列表linklist中,然後利用索引進行兩兩對調,最後重新連接這個鏈表,然後linklist[0]
代碼如下:
#!/usr/bin/env python # -*- coding:utf-8 -*- class Solution:def swapPairs(self, head): #思路非常簡單,把鏈表遍歷出來放到列表裏,然後再兩兩對調,在重新鏈接鏈表。 linklist = [] x, y = 0, 1 while head != None: #將鏈表遍歷到一個linklist列表中 linklist.append(head) head=head.next if len(linklist)<1: #這裏排除一下特殊情況,如果給的鏈表為空,則直接返回空值 returnlinklist while y <= len(linklist)-1: #這裏進行兩兩對調 linklist[x], linklist[y] = linklist[y], linklist[x] x, y = x + 2, y + 2 for i in range(len(linklist)-1): #將對調後的linklist鏈接成新的鏈表 linklist[i].next=linklist[i+1] linklist[-1].next=None #設置鏈表最後一個值的末端為空值 return linklist[0]
LeetCode算法題python解法:24. Swap Nodes in Pairs