成對交換鏈表節點
Swap Nodes in Pairs
- 給定一個鏈表,成對交換兩個節點,返回新鏈表的頭部,不允許使用額外的內存,只能在原有鏈表節點基礎上進行操作。
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.
example 1
input: 1 -> 2 -> 3 -> 4
output: 2 -> 1 -> 4 -> 3
思路
- 可以使用兩個指針,指向當前需要交換的兩個節點,交換之後向鏈表尾部移動。
- 交換節點是一種方法,另外一種取巧的方法是,不交換節點,只交換節點的值
代碼
# Definition for singly-linked list.
class ListNode(object):
def __init__(self, x):
self.val = x
self.next = None
class Solution(object):
def swapPairs(self, head):
"""
:type head: ListNode
:rtype: ListNode
"""
try:
prev = head
tail = prev.next
while True:
prev.val, tail.val = tail.val, prev.val
prev = tail.next
tail = prev.next
finally:
return head
本題以及其它leetcode題目代碼github地址: github地址