leetcode鏈表題心得

83.刪除排序列表中的重複元素

給定一個排序鏈表,刪除所有重複的元素,使得每個元素只出現一次。

示例 1:

輸入: 1->1->2
輸出: 1->2

示例 2:

輸入: 1->1->2->3->3
輸出: 1->2->3

思路一:直接方法:

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

class Solution:
    def deleteDuplicates(self, head: ListNode) -> ListNode:
        if head:
            cur = head
            while cur and cur.next:
                if cur.val == cur.next.val:
                    cur.next = cur.next.next
                else:
                    cur = cur.next
            return head
                    
            

思路二:遞歸法

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

class Solution:
    def deleteDuplicates(self, head: ListNode) -> ListNode:
        if head:
            cur = head
            if cur.next is None:
                return cur
            if cur.val == cur.next.val:
                cur.next = cur.next.next
                cur = self.deleteDuplicates(cur)
                return cur
            else:
                cur.next = self.deleteDuplicates(cur.next)
                return cur
                    
            

876.鏈表的中心結點

給定一個帶有頭結點 head 的非空單鏈表,返回鏈表的中間結點。

如果有兩個中間結點,則返回第二個中間結點。

示例 1:

輸入:[1,2,3,4,5]
輸出:此列表中的結點 3 (序列化形式:[3,4,5])
返回的結點值爲 3 。 (測評系統對該結點序列化表述是 [3,4,5])。
注意,我們返回了一個 ListNode 類型的對象 ans,這樣:
ans.val = 3, ans.next.val = 4, ans.next.next.val = 5, 以及 ans.next.next.next = NULL.

示例 2:

輸入:[1,2,3,4,5,6]
輸出:此列表中的結點 4 (序列化形式:[4,5,6])
由於該列表有兩個中間結點,值分別爲 3 和 4,我們返回第二個結點。

提示:

  • 給定鏈表的結點數介於 1 和 100 之間。

思路一:將鏈表中的值放在數組中,使用切片方式獲得後半部分值。

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

class Solution:
    def middleNode(self, head: ListNode) -> ListNode:
        if head.next is None:
            return head
        else:
            list=[]
            cur = head
            while cur is not None:
                list.append(cur.val)
                cur = cur.next
            return list[int(len(list)/2):]

思路二:快慢指針法,慢指針每次走一步,快指針每次走兩步,當快指針走完,返回慢指針。

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

class Solution:
    def middleNode(self, head: ListNode) -> ListNode:
        if head.next is None:
            return head
        else:
            slow = head
            fast = head
            while fast and fast.next:
                slow = slow.next
                fast = fast.next.next

            return slow

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章