主题:[讨论]删除多链表中值相同的多余节点 算法
kuyuy
[专家分:0] 发布于 2007-09-28 00:39:00
谁能帮我啊 即一个链表中多个节点有相同的数据域,只保留其中一个,其余删除。
谁能给个算法啊
回复列表 (共2个回复)
沙发
goal00001111 [专家分:4030] 发布于 2007-09-28 09:07:00
希望不是求作业.
写了一个简单的,请参考!
[code=c]
/*
Name:
Copyright:
Author:
Date: 28-09-07 08:50
Description: 一个链表中多个节点有相同的数据域,只保留其中一个,其余删除。
*/
#include <iostream>
#include <string>
using namespace std;
typedef char ElemType;
typedef struct LinkNode
{
ElemType data;
LinkNode *next;
} *LNode;
LNode CreateLink(LNode head, ElemType a);
void Print(LNode head);
void Delete(LNode pre);//删除pre之后的结点
void Search(LNode head);
int main()
{
char a[] = "123122afefadweaaefaeaae2332";
int len = strlen(a);
LNode head = NULL;
for (int i=len-1; i>=0; --i)
head = CreateLink(head, a[i]);
Print(head);
Search(head);
Print(head);
getchar();
return 0;
}
LNode CreateLink(LNode head, ElemType a)//从头部插入一个新结点
{
LNode s = new LinkNode;
if (!s)
{
printf("Out of space!");
exit (1);
}
s->data = a;
s->next = NULL;
//链表的头指针指向新结点
if (!head)
head = s;
else
{
s->next = head;
head = s;
}
return head;
}
void Print(LNode head)//输出链表
{
LNode p = head;
while (p)
{
cout << p->data << ' ';
p = p->next;
}
cout << endl;
}
void Delete(LNode pre)//删除pre之后的结点
{
LNode p = pre->next;
pre->next = p->next;
delete p; //删除该结点
}
void Search(LNode head)//查找多余的结点,并删除它
{
if (!head)
return ;
LNode p, q, pre;
p = head;
while (p)//遍历链表查找多余的结点
{
pre = p;
q = pre->next;
while (q)//遍历链表查找与结点p相同的结点
{
if (q->data == p->data)//如果相同,删除该结点
{
Delete(pre);
q = pre->next;
}
else//否则往下查找
{
pre = q;
q = q->next;
}
}
p = p->next;
}
}
[/code]
板凳
SmartY0622 [专家分:0] 发布于 2007-09-28 19:08:00
//遍历同时插入的时间复杂度为(n^2),
//if we sort it firstly, the the complexity is o(nlogn + n);
//so i think sort firstly is better than others especially when the number of element is large.
我来回复