Lintcode-remove Duplicates from Sorted List
- Lintcode-remove Duplicates from Sorted List
- Web Link
- Description
- Code-c
- Tips
Web Link
http://www.lintcode.com/en/problem/remove-duplicates-from-sorted-list/
Description
Given a sorted linked list, delete all duplicates such this each element appear only once.
Example
Given 1->1->2, return 1->2.
Given 1->1->2->3->3, return 1->2->3.
Code-c++
/** * Definition of ListNode * class ListNode {* Public: * int val; * ListNode *next; * ListNode (int val) {* This->val = val; * This->next = NULL; *} *} * * class solution {Public/** * @param head:the first node of linked list. * @return: Head node */ListNode *deleteduplicates (ListNode *head) {//Write your code herelistnode* current = head; listnode* Next_next;if(current = = NULL) {returnNULL; } while(Current->next! = NULL) {if(current->Val= = Current->next->Val) {Next_next = current->next->next; Delete current->next; Current->next = Next_next; }Else{current = current->next; } }returnHead }};
Tips
Algorithm:
Traverse the list from the head (or start) node. While traversing, the compare each node and its next node. If data of next node is same as current node then delete the next node. Before we delete a node, we need to store next pointer of the node
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
Lintcode-remove Duplicates from Sorted List