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
.
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) {//这个链表不包含头节点
ListNode* p = head;
ListNode* ret = p;//保存返回链表指针
while (head != NULL) {
int val = head->val;
while (head != NULL&&head->val == val)
head = head->next;
p->next = head;
p = p->next;//这里需要往后移一位
}
return ret;
}
};