1. 程式人生 > 其它 >Leetcode24:兩兩交換連結串列中的節點python實現

Leetcode24:兩兩交換連結串列中的節點python實現

技術標籤:Leetcode連結串列leetcode演算法

給定一個連結串列,兩兩交換其中相鄰的節點,並返回交換後的連結串列。

你不能只是單純的改變節點內部的值,而是需要實際的進行節點交換。

# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, x):
#         self.val = x
#         self.next = None

class Solution:
    def swapPairs(self, head):
        if not head or
not head.next: return head first=head second=head.next first.next=self.swapPairs(second.next) second.next=first return second