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
.
题目本身很简单 但是要注意判断空链表情况。。 提交了3次才ac
/**
* 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) {
// Note: The Solution object is instantiated only once and is reused by each test case.
if (head == NULL) return NULL;
ListNode* curPtr = head, *comparePtr = head->next;
while (comparePtr)
{
if (comparePtr->val == curPtr->val)
{
curPtr->next = comparePtr->next;
}
else
curPtr = comparePtr;
comparePtr = comparePtr->next;
}
return head;
}
};