Topic link
The original title of https://leetcode.com/problems/remove-duplicates-from-sorted-list/
Given a sorted linked list, delete all duplicates such which each element is appear only once.
For example,
Given 1->1->2, return 1->2.
Given 1->1->2->3->3, return 1->2->3. Title Translation
Given an ordered list, delete the repeating element so that each element appears once. method of Thinking idea of a
Iterate through all the nodes, for each node, check that a subsequent node is the same as the current node value, and delete the following nodes if the same. Cycle down.
Code
# Definition for singly-linked list.
# class ListNode (object):
# def __init__ (self, x):
# self.val = x
# Self.next = None
class Solution (object):
def deleteduplicates (self, head): ""
: Type Head:listnode
: Rtype:listnode "" "
p = head while
p:
if p.next and p.next.val = = P.val:
p.next = p.next.next
Else:
p = p.next return head
Idea two
Iterate through all the nodes, for each node, start from the last node and check for the same value as the current node until you find a later node whose value is different from the current node, removing all nodes in the middle that are the same as the current node values. Cycle down.
Code
# Definition for singly-linked list.
# class ListNode (object):
# def __init__ (self, x):
# self.val = x
# Self.next = None
class Solution (object):
def deleteduplicates (self, head): ""
: Type Head:listnode
: Rtype:listnode "" "
p = q = head while
p: while Q and
q.val = p.val:
q = q.next
p.next = q
p = q
return Head
idea three
Recursive implementations are essentially checking for the same node from the backward forward.
Code
# Definition for singly-linked list.
# class ListNode (object):
# def __init__ (self, x):
# self.val = x
# Self.next = None
class Solution (object):
def deleteduplicates (self, head): ""
: Type Head:listnode
: Rtype:listnode ' "' if not '
or not '
Head.next: Return head
head.next = self.deleteduplicates (head.next)
Return head if Head.val!= head.next.val else head.next
PS: Novice Brush Leetcode, new handwritten blog, write wrong or write not clear also please help point out, thank you.
reprint Please specify: http://blog.csdn.net/coder_orz/article/details/51506143