Remove Duplicates from Sorted List
#include "iostream"
using namespace std;
/**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) {
if (head==NULL) {
return head;
}
ListNode *res=head;
ListNode *p=head;
ListNode *q=head;
int temp=head->val;//设置一临时变量存储当前出现的第一个值
while (p!=NULL) {
while (temp==p->val) {//注意此处使用while,而非if
p=p->next;
if (p==NULL) {
break;
}
}
q->next=p;
q=q->next;
if (p==NULL) {
break;
}
//注意此处赋值要在p!=NULL时
temp=q->val;
p=p->next;
}
return res;
}
};
int main() {
ListNode *t=new ListNode(1);
t->next=new ListNode(1);
cout<<t->val<<endl;
Solution so;
ListNode *res= so.deleteDuplicates(t);
cout<<res->val<<endl;
return 0;
}