Given the
head
of a sorted linked list, delete all duplicates such that each element appears only once. Return the linked list sorted as well.Example 1:
Input: head = [1,1,2] Output: [1,2]Example 2:
Input: head = [1,1,2,3,3] Output: [1,2,3]Constraints:
- The number of nodes in the list is in the range
[0, 300]
.-100 <= Node.val <= 100
- The list is guaranteed to be sorted in ascending order.
题目大意:
这道题就是让你删掉一个升序链表中值重复的结点 。
实现思路:
不是很难,就不说了。
实现代码:
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode() : val(0), next(nullptr) {}
* ListNode(int x) : val(x), next(nullptr) {}
* ListNode(int x, ListNode *next) : val(x), next(next) {}
* };
*/
class Solution {
public:
ListNode* deleteDuplicates(ListNode* head) {
ListNode* t=head;
ListNode* p=NULL;
while(t){
while(t->next&&t->next->val==t->val){
p=t->next;
t->next=p->next;
delete p;
}
t=t->next;
}
return head;
}
};
这里注意最后释放内存,最好用delete,我用free一起不对。不知道为什么,如果有知道的希望可以教教我。