题目大意:删除链表中的重复元素
分析:考察链表的删除节点操作。遍历链表删除和前一节点数字相同的结点即可。
代码:
/**
* 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 *pre = head;
if (pre == NULL || pre->next == NULL) return head;
ListNode *p = head->next;
while (pre != NULL && p != NULL) {
if (pre->val == p->val) {
pre->next = p->next;
delete p;
p = pre->next;
}
else {
pre = pre->next;
p = p->next;
}
}
return head;
}
};