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
.
判断比较节点为空后,别忘了把当前节点的下一个指针指向空,否则,就没有完成此种情况下的清空操作。
/**
* 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 *cur_node,*comp_node;
if(NULL == head)
{
return NULL;
}
cur_node = head;
comp_node = head->next;
while(NULL!=comp_node)
{
if(cur_node->val != comp_node->val)
{
cur_node->next = comp_node;
cur_node = comp_node;
}
comp_node = comp_node->next;
}
cur_node -> next = NULL;
return head;
}
};