题目描述
在一个排序的链表中,存在重复的结点,请删除该链表中重复的结点,重复的结点不保留,返回链表头指针。 例如,链表1->2->3->3->4->4->5 处理后为 1->2->5
思路:没啥想法,就照字面意思来
// 删除链表中重复的结点.cpp : 定义控制台应用程序的入口点。
//
#include "stdafx.h"
#include<iostream>
using namespace std;
struct ListNode {
int val;
struct ListNode *next;
ListNode(int x) :
val(x), next(NULL) {
}
};
ListNode* deleteDuplication(ListNode* pHead)
{
if (pHead == NULL) return NULL;
if (pHead&&pHead->next == NULL) return pHead;
ListNode* pre = new ListNode(1); //如果结点重复不是在头结点,pre申明成NULL(无所谓),如果结点重复从头结点开始,则需要当前结点的前一个结点pre->next,需赋值初始化,想法是初始化3个结点,pre,cur,next,一一比较过去,有重复就删除
ListNode* cur = pHead;
pre->next = cur;
ListNode* pre1 = pre;
ListNode* head = cur;
ListNode* next = pHead->next;
while (cur&&next)
{
if (cur->val != next->val)//如果不等
{
pre = cur;
cur = cur->next;
next = next->next;
}
else
{//相等,因为是经过排序的列表
while (next)//接着寻找值一样的结点
{
next = next->next;
if (next)//结点不为NULL
{
if (cur->val == next->val)
{
continue;//相等的话继续往下找
}
else
{
break;//如果不等则跳出循环
}
}
else {//如果为NULL,则说明cur后面的全部相等,应该全部删除包括(cur)
break;
}
}
if (next == NULL)//判断,next为NULL,,则说明cur后面的全部相等,应该全部删除包括(cur)
{
pre->next = next;
break;
}
pre->next = next;//全部删除包括(cur)
cur = next;
next = next->next;
}
}
return pre1->next;
}
int main()
{
ListNode * root = new ListNode(2);
ListNode * root1 = new ListNode(2);
ListNode * root2 = new ListNode(3);
ListNode * root3 = new ListNode(3);
ListNode * root4 = new ListNode(4);
ListNode * root5 = new ListNode(4);
ListNode * root6 = new ListNode(5);
root->next = root1;
root1->next = root2;
root2->next = root3;
root3->next = root4;
root4->next = root5;
root5->next = root6;
root6->next = NULL;
ListNode * head = deleteDuplication(root);
while (head)
{
cout << head->val << endl;
head = head->next;
}
system("pause");
return 0;
}
精简一下代码
class Solution {
public:
ListNode* deleteDuplication(ListNode* pHead)
{
ListNode* p = pHead;
ListNode* head=new ListNode(0); //初始化一个结点,原因同上
ListNode* q = head;
while(p){
while(p!=NULL&&p->next!=NULL&&p->next->val==p->val){//如果相等,则接着往后
int temp = p->val;
while(p!=NULL&&p->val==temp){
p = p->next;
}
}
q->next = p//变相删除中间相等节点
q=q->next;//q移动到当前结点
if(p) p = p->next;//如果p不为NULL,结点移动到下一个
}
return head->next;
}
};
看到一个递归的版本,自己写不出来,还是贴出来吧
class Solution {
public:
ListNode* deleteDuplication(ListNode* pHead)
{
if (pHead==NULL)
return NULL;
if (pHead!=NULL && pHead->next==NULL)
return pHead;
ListNode* current;
if ( pHead->next->val==pHead->val){
current=pHead->next->next;
while (current != NULL && current->val==pHead->val)
current=current->next;
return deleteDuplication(current); //这里用递归很有意思
}
else {//如果不相等
current=pHead->next;//当前结点往后移一个
pHead->next=deleteDuplication(current);//递归
return pHead;
}
}
};