笔试代码题--删除链表中的重复结点
题目描述:
删除链表中重复的节点
在一个排序,如何删除重复的节点?
例如:1 -> 2 -> 3 -> 3 -> 4
删除后是 1 -> 2 -> 4
代码如下:用三指针法:
ListNode* deleteDuplication(ListNode* pHead)
{
// 先判断空
if (pHead == NULL)
{
return NULL;
}
// 判断是否只有一个节点
if (pHead->next == NULL)
{
return pHead;
}
// 我们采用带头链表,自己添加一个头
ListNode* pre = new ListNode();
pre->next = pHead; // 把头节点链接在链表上
ListNode* pre_head = pre; // 用来保存头节点,用于返回删除后的链表
ListNode* cur = pHead; //中指针
ListNode* nex = pHead->next; // 后面指针
while (nex != NULL) // 结束条件
while (nex != NULL && cur->val == nex->val)
{
nex = nex->next;
}
// 如果没有重复的那么cur的next一定等于nex
if (cur->next != nex) // 如果相等说明没有相同的节点
{
while (cur != nex) // 删除动作
{
pre->next = cur->next;
delete cur;
cur = pre->next;
}
if (nex != NULL) // 这里一定要要注意,要防止走到NULL发生段错误
nex = nex->next;
}
else
{
// 处理没有重复的情况
pre = cur;
nex = nex->next;
cur = cur->next;
}
}
ListNode* head = pre_head->next; // 释放空间,防止内存泄漏
delete pre_head;
return head;
}