题解 | #删除有序链表中重复的元素-I#
删除有序链表中重复的元素-I
http://www.nowcoder.com/practice/c087914fae584da886a0091e877f2c79
双指针
用双指针遍历链表,有重复的直接进行删除操作,注意初始化
C++代码:
class Solution {
public:
ListNode* deleteDuplicates(ListNode* head) {
if (!head || !head->next) {return head;}
ListNode *pre = head, *p = head->next;
while (p) {
if (pre->val == p->val) {
pre->next = p->next;
} else {
pre = p;
}
p = p->next;
}
return head;
}
};