83. Remove Duplicates from Sorted List
我的思路:
只要找到相同的就删除后面的那个元素
最快解法的答案:
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
/*
Algo:
M1: two pointers method(mine): p1 and p2. p2 always points to the non-duplicate node after the first while.
CC: empty LL and one node LL
Notes:
1. we should delete the duplicate nodes using delete or free
*/
class Solution {
public:
ListNode* deleteDuplicates(ListNode* head) {
if(head == NULL || head->next == NULL)
return head;
ListNode *p1, *p2;
p1 = head;
p2 = p1->next;
while(p1 && p2){ // better than "while(p1!=NULL && p2!=NULL)"
while(p2 && p1->val == p2->val)
p2 = p2->next; // Should we delete here?
if(p2){
p1->next = p2;
p1 = p2;
p2 = p1->next;
}
else
p1->next = NULL;
}
return head;
}
};
这个效率差的有点多。。。我感觉自己不怎么会链表啊,之后一段时间先补一补链表的知识吧。