Title: http://oj.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 all duplicate elements so that each element appears only once.
For example
Given 1->1->2, returns 1->2.
Given 1->1->2->3->3, returns 1->2->3.
Analysis:
Each element is retained only once, and multiple duplicate elements are deleted once.
C + + implementation:
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode (int x): Val (x), Next (NULL) {}
*};
* *
class Solution {public
:
listnode *deleteduplicates (ListNode *head) {
if (head = = NULL | | head- >next = = NULL) {return head
;
}
ListNode *pre = head;
ListNode *cur = head->next;
while (cur!= NULL)
{
if (cur->val!= pre->val)
{
pre = cur;
cur = cur->next;
Continue;
}
while (Cur->next!= NULL && cur->next->val = = pre->val)
{
cur = cur->next;
}
Pre->next = cur->next;
cur = pre->next;
}
return head;
}
;
Java implementation:
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode Next;
* ListNode (int x) {
* val = x;
* next = null;
* }
*/
public
class Solution {public
listnode deleteduplicates (ListNode head) {
if ( Head = = NULL | | Head.next = = null) {return head
;
}
ListNode pre = head;
ListNode cur = head.next;
while (cur!= null) {
if (cur.val!= pre.val) {
pre = cur;
cur = cur.next;
Continue;
}
while (Cur.next!= null && cur.next.val = = pre.val) {
cur = cur.next;
}
Pre.next = Cur.next;
cur = pre.next;
}
return head;
}
Python implementations:
# Definition for singly-linked list.
# class ListNode:
# def __init__ (self, x):
# self.val = x
# Self.next = None
class Solution :
# @param head, a listnode
# @return a listnode
def deleteduplicates (self, head):
if head = = None or He Ad.next = none: Return head
pre =
cur = head.next while
cur!= none:
if Cur.val!=:
pre = cur
cur = cur.next
continue while
Cur.next!= None and Cur.next.val = = Pre.val:
cur = cur. Next
pre.next = cur.next
cur = pre.next return head
Thank you for reading and welcome comments.