Remove duplicates from sorted list
Given a sorted Linked List, delete all duplicates such that each element appear only once.
For example,
Given1->1->2
, Return1->2
.
Given1->1->2->3->3
, Return1->2->3
.
It is very simple. First, judge whether the first position is null. If it is not empty, then judge whether the next position is null. If it is empty, no operation is required. If neither of them is blank, you can compare them. If they are the same, delete them (point to the next location). If they are different, the Pointer Points to the next location.
/** * 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) { ListNode *p; p=head; while(p!=NULL) { if(p->next!=NULL) { if(p->val==p->next->val) p->next=p->next->next; else p=p->next; } else return head; } return head; }};
Leetcode remove duplicates from sorted list