简繁EN

LeetCodeNo. 036

【LeetCode with Python】 24. Swap Nodes in Pairs

目錄

題目

原題頁面:https://leetcode.com/problems/swap-nodes-in-pairs/
題目型別:Linked List
難度評價:Medium
類似題目:(H) Reverse Nodes in k-Group

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.


分析

交換單鏈表中每一對相鄰的奇偶數下標的元素,注意防止連結串列長度可能是奇數,即不要忘記檢查second_node是否為None。


程式碼

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
class Solution:
# @param a ListNode
# @return a ListNode
def swapPairs(self, head):
if None == head:
return head
new_head = ListNode(0)
new_head.next = head
last_node = new_head
while True:
first_node = last_node.next
if None == first_node:
break
second_node = first_node.next
if None == second_node:
break
last_node.next, first_node.next, second_node.next, last_node = second_node, second_node.next, first_node, first_node
return new_head.next

本文地址:https://xnerv.wang/zh-tw/leetcode-swap-nodes-in-pairs/