83. Remove Duplicates from Sorted List
Description
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.
Solution
- 题意即给定一个排好序的链表数组,让你把其中重复的数字删除至只剩一个。
- 这是一个变相的删除节点程序,只需要对和前一个节点相同的节点删除即可,代码如下
class Solution {
public:
ListNode* deleteDuplicates(ListNode* head) {
if (!head) return NULL;
ListNode *pre = head,*cur;
cur = head->next;
while (cur) {
if (pre->val == cur->val) {
pre->next = cur->next;
}
else {
pre = pre->next;
}
cur = cur->next;
}
return head;
}
};