leetcode 24 兩兩交換連結串列中的節點
阿新 • • 發佈:2018-12-07
給定一個連結串列,兩兩交換其中相鄰的節點,並返回交換後的連結串列。
示例:
給定 1->2->3->4, 你應該返回 2->1->4->3.
說明:
你的演算法只能使用常數的額外空間。
你不能只是單純的改變節點內部的值,而是需要實際的進行節點交換。
# Definition for singly-linked list. # class ListNode: # def __init__(self, x): # self.val = x # self.next = None class Solution: def swapPairs(self, head): """ :type head: ListNode :rtype: ListNode """ res=[] if not head: return None while head: res.append(head.val) head = head.next for i in range(int(len(res)/2)): res[2*i],res[2*i + 1] = res[2*i + 1],res[2*i] return res