Given a sorted linked list, delete all duplicates such this each element appear only once.
For example,
Given 1->1->2 , return 1->2 .
Given 1->1->2->3->3 , return 1->2->3 .
Title Requirements:
To an ordered list, delete duplicate nodes, so that each element appears only once.
Problem Solving Ideas:
1, through the chain list, if the front and back two nodes are the same, then the first node points to its lower node, and delete its next node.
2, recursive thinking.
Code:
/** Definition for singly-linked list. * struct ListNode {* int val; * ListNode *next; * ListNode (int x) : Val (x), Next (NULL) {}}; */classSolution { Public: ListNode*deleteduplicates (ListNode *head) {ListNode*lst=Head; ListNode*del; while(LST && lst->next) { if(lst->val==lst->next->val) {del=lst->Next; LST->next=lst->next->Next; Delete(DEL); } ElseLST=lst->Next; } returnHead; }};
/** Definition for singly-linked list. * struct ListNode {* int val; * ListNode *next; * ListNode (int x) : Val (x), Next (NULL) {}}; */classSolution { Public: ListNode*deleteduplicates (ListNode *head) { if(Head==null | | head->next==NULL)returnHead; if(head->val==head->next->val) head=deleteduplicates (head->next); ElseHead->next=deleteduplicates (head->next); returnHead; }};
(Leetcode) Remove duplicates from Sorted Lists