Given a sorted linked list, delete all nodes that have duplicate numbers, leaving only distinct numbers from the original list.
Example 1:
Input: 1->2->3->3->4->4->5
Output: 1->2->5
Example 2:
Input: 1->1->1->2->3
Output: 2->3
这个题目没做到,很不应该,删除这种题目以后记得用双指针,一个pre指针指向前一个,另一个cur指针去遍历是否有重复,如果pre->next == cur 说明没有重复的数字,如果不等说明有重复.这是非递归
/**
* 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* fakeHead = new ListNode(0);
fakeHead->next = head;
ListNode* pre = fakeHead;
ListNode* cur = head;
while(cur!=NULL){
while(cur->next!=NULL && cur->val==cur->next->val){
cur = cur->next;
}
if(pre->next==cur){
pre = pre->next;
}
else{
pre->next = cur->next;
}
cur = cur->next;
}
return fakeHead->next;
}
};
这种题目也可以用递归,递归主要是要有终止条件,
第一个终止条件是当head==NULL 时返回NULL
第二个是当出现重复的时候 返回重复完的第一个
第三个是没用重复时head->next = 递归函数
public ListNode deleteDuplicates(ListNode head) {
if (head == null) return null;
if (head.next != null && head.val == head.next.val) {
while (head.next != null && head.val == head.next.val) {
head = head.next;
}
return deleteDuplicates(head.next);
} else {
head.next = deleteDuplicates(head.next);
}
return head;
}
class Solution {
public:
ListNode* deleteDuplicates(ListNode* head) {
if (!head) return 0;
if (!head->next) return head;
int val = head->val;
ListNode* p = head->next;
if (p->val != val) {
head->next = deleteDuplicates(p);
return head;
} else {
while (p && p->val == val) p = p->next;
return deleteDuplicates(p);
}
}
};