Given a sorted linked list, delete all duplicates such that each element appear only once.
Example 1:
Input: 1->1->2 Output: 1->2
Example 2:
Input: 1->1->2->3->3 Output: 1->2->3
链表是基本的数据结构,无论是面试还是工作中,都会经常遇到,可惜之前一直没能重视起来。本题是easy的级别,但是链表的访问和删除功底太薄弱,看了别人的答案才能做出来。由于是排好序的链表,所以本题只需要在非空节点的条件下判断相等的情况并删除相应的节点(指向下一节点)即可,代码记录如下:
/**
* 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 = head;
if(NULL == head || NULL == head->next)
return head;
while(NULL != p->next)
{
if(p->val == p->next->val)
{
ListNode *tmp = p->next;
p->next = tmp->next;
//delete tmp; //delete here?
continue;
}
p = p->next;
}
return head;
}
};