题目
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.
分析
该题目与LeetCode 83题目类似,都是删除链表中重复元素的题目。
该题目要求只保存不重复的结点!
详细见代码!
AC代码
class Solution {
public:
ListNode *deleteDuplicates(ListNode *head) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
if (head == NULL || head->next == NULL)
return head;
ListNode * p = head;
while (p->next != NULL && p->val == p->next->val)
{
p = p->next;
}
//保存结点
ListNode *r = p->next;
//如果头结点是重复的
if (p != head){
while (head != r)
{
ListNode * tmp = head;
head = head->next;
free(tmp);
}
return deleteDuplicates(head);
}
//否则递归处理接下来的结点
head->next = deleteDuplicates(head->next);
return head;
}
};