leetCode The first 83 topic , Delete duplicate elements from the sort list
Example 1:
Input :head = [1,1,2]
Output :[1,2]
Example 2:
Input :head = [1,1,2,3,3]
Output :[1,2,3]
Tips :
The number of nodes in the linked list is in the range [0, 300] Inside
-100 <= Node.val <= 100
The title data ensures that the linked list has been in ascending order array
The title has explained that the linked list itself is in ascending order , Then there is only repetition before and after , There will be no situation that the back is smaller than the front , So just traverse the linked list , In the case of equality , Just delete the last element
# python3
class Solution:
def deleteDuplicates(self, head: ListNode) -> ListNode:
if head == None:
return head
currentNode = head
while currentNode.next != None :
if currentNode.next.val == currentNode.val:
currentNode.next = currentNode.next.next
else:
currentNode = currentNode.next
return head
When we write code , Can feel , When the elements from the front to the back are spliced into a new ordered table , In fact, it is the same operation as a shorter linked list after spelling an element , So let's try recursion .
If the header pointer is null , Or the next one in the header pointer is null , Directly back to the header pointer .
If the next non null of the header pointer , Then the head pointer and the linked list after the head pointer are spliced , Call itself directly .head.next = self.deleteDuplicates(head.next)
For the returned head.next Linked list part , If its value and head.val equal , So directly head discarded , return head.next. Otherwise, we will not deal with it , return head.
# python3
class Solution1:
def deleteDuplicates(self, head: ListNode) -> ListNode:
if head == None or head.next == None:
return head
head.next = self.deleteDuplicates(head.next)
if head.val == head.next.val: # If the latter is as big as the former , Then only the last one will be returned
return head.next
else: # The former is smaller than the latter , Meet the requirements , Go straight back to
return head
The wide application of the In
文章目錄概述設置步驟使用WSL在windows上跑ubunt