I. Question
Given a sorted Linked List, delete all duplicate nodes so that each node appears only once.
For example:
Given 1-> 1-> 2, return 1-> 2.
Given 1-> 1-> 2-> 3-> 3, return1-> 2-> 3.
Ii. Analysis
When I first saw the question, I didn't see the sorted keyword. I thought I would use an array or space to save the node, and then save it every time ....... I still don't catch a cold in English! Therefore, it is very easy to traverse directly. If it is repeated, delete OK directly. Otherwise, move it directly to the next node. When comparing nodes, note that it is OK for empty nodes!
/** * 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* point; point = head; while(point) { if(point->next&&point->val==point->next->val) point->next=point->next->next; else point=point->next; } return head; }};
Leetcode: remove_duplicates_from_sorted_list