程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式師世界 >> 編程語言 >  >> 更多編程語言 >> Python

Delete duplicate elements in the sorting linked list -python

編輯:Python

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

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式師世界 All Rights Reserved