7

(Remove Duplicates from Sorted List)

 2 years ago
source link: https://tianrunhe.wordpress.com/2012/08/25/remove-duplicates-from-sorted-list/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

(Remove Duplicates from Sorted List)

25 Aug 2012 3 Comments

by Runhe Tian in LeetCode Tags: C++, Java, Linked List

Given a sorted linked list, delete all duplicates such that each element appear only once.
For example,
Given 1->1->2, return 1->2.
Given 1->1->2->3->3, return 1->2->3.

Thoughts:
This question is the same as ‘remove duplicates from sorted array’ except that we need to deal with linked list this time. The algorithm is the same.

Code (Java):

public class Solution {
public ListNode deleteDuplicates(ListNode head) {
if(head == null)
return null;
ListNode j = head;
ListNode i = head.next;
while(i != null) {
if(j.val != i.val) {
j = j.next;
j.val = i.val;
}
i = i.next;
}
j.next = null;
return head;
}
}

Code (C++):

class Solution {
public:
ListNode *deleteDuplicates(ListNode *head) {
if(head == NULL)
return head;
ListNode *j = head;
ListNode *i = j -> next;
while(i != NULL) {
if(i -> val != j -> val) {
j = j -> next;
j -> val = i -> val;
}
i = i -> next;
}
j -> next = NULL;
return head;
}
};

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK