1. 程式人生 > 其它 >LeetCode第二十四題—Python實現

LeetCode第二十四題—Python實現

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


title: LeetCode No.24

categories:

  • OJ
  • LeetCode

tags:

  • Programing
  • LeetCode
  • OJ

LeetCode第二十四題

題目描述

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

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

figure.1

示例 1:

輸入:head = [1,2,3,4]
輸出:[2,1,4,3]
示例 2:

輸入:head = []
輸出:[]
示例 3:

輸入:head = [1]
輸出:[1]

提示:

連結串列中節點的數目在範圍 [0, 100] 內
0 <= Node.val <= 100

程式碼

除了本題的辦法,同樣也可以採用遞迴的方法進行操作,因此都是相同的操作。

# Definition for singly-linked list.
# class ListNode(object):
#     def __init__(self, val=0, next=None):
#         self.val = val
#         self.next = next
class Solution(object):
    def swapPairs(self, head):
        """
        :type head: ListNode
        :rtype: ListNode
        """
        if head == None:
            return None

        if head.next == None:
            return head

        res = ListNode(None)
        res = head

        while True:
            if head == None:
                break
            if head.next == None:
                break
            temp = head.val
            nextNode = head.next
            head.val = nextNode.val
            nextNode.val = temp
            head = head.next.next
        return res