JZ76 删除链表中重复的结点
删除链表中重复的结点
https://www.nowcoder.com/practice/fc533c45b73a41b0b44ccba763f866ef?tpId=13&tqId=23450&ru=/ta/coding-interviews&qru=/ta/coding-interviews/question-ranking
/*
struct ListNode {
int val;
struct ListNode *next;
ListNode(int x) :
val(x), next(NULL) {
}
};
*/
/*
方法一:
时间复杂度:O(n),空间复杂度O(1)
*/
class Solution {
public:
ListNode* deleteDuplication(ListNode* pHead) {
ListNode* cur = pHead;
ListNode* pre = new ListNode(-1); //在头节点之前建立一个结点
ListNode* ans = pre;
pre->next = pHead;
while(cur)
{
if(cur->next && cur->val == cur->next->val)
{
cur = cur->next;
while(cur->next && cur->val == cur->next->val)
{
cur = cur->next;
}
pre->next = cur->next;
cur = cur->next;
}
else
{
pre = cur;
cur = cur->next;
}
}
return ans->next;
}
};