删除排序链表中的重复元素
题目链接
解题思路
1.遇见相同的元素直接删除即可
2.链表的头部也可能是重复元素,所以需要一个哑节点res来指向链表的头节点
/*** 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) {if(!head){return head;}ListNode* res = new ListNode(0,head);ListNode * cur = res;while(cur->next && cur->next->next){if(cur->next->val == cur->next->next->val){int x = cur->next->val;while(cur->next && cur->next->val == x){cur->next = cur->next->next;}}else{cur = cur->next;}}return res->next;}
};