在一个排序的链表中,存在重复的结点,请删除该链表中重复的结点,重复的结点不保留。 例如,链表1->2->3->3->4->4->5 处理后为 1->2->3->4->5,用c语言写代码。
时间: 2024-05-07 19:15:15 浏览: 111
```c
struct ListNode* deleteDuplication(struct ListNode* pHead)
{
if(pHead == NULL || pHead->next == NULL)
return pHead;
struct ListNode* pPreNode = NULL;
struct ListNode* pNode = pHead;
while(pNode != NULL)
{
struct ListNode* pNext = pNode->next;
bool needDelete = false;
if(pNext != NULL && pNode->val == pNext->val)
needDelete = true;
if(!needDelete)
{
pPreNode = pNode;
pNode = pNode->next;
}
else
{
int val = pNode->val;
struct ListNode* pToBeDel = pNode;
while(pToBeDel != NULL && pToBeDel->val == val)
{
pNext = pToBeDel->next;
free(pToBeDel);
pToBeDel = NULL;
pToBeDel = pNext;
}
if(pPreNode == NULL)
pHead = pNext;
else
pPreNode->next = pNext;
pNode = pNext;
}
}
return pHead;
}
```
阅读全文