/*用单链表保存m个整数,结点的结构为data、link,且|data|<=n(n为正整数)。现要求设计一个时间复杂度尽可能
高效的算法,对于链表中data的绝对值相等的结点,仅保留第一次出现的结点而删除其余绝对值相等的结点。例如
{21,-15,-15,-7,15}->{21,-15,-7}*/
方法一:
#include<stdio.h>
#include<stdlib.h>
typedef int ElemType;
typedef struct LNode{
ElemType data;
struct LNode *link;
}LNode,*LinkList;
LinkList tailInsertList(LinkList &L)
{
ElemType x;
L = (LinkList)malloc(sizeof(LNode));
LNode *r=L;
scanf("%d",&x);
while(x!=9999)
{
LNode *s = (LNode*)malloc(sizeof(LNode));
s->data = x;
r->link = s;
r = s;
scanf("%d",&x);
}
r->link = NULL;
return L;
}
int fabs(int x)
{
if(x<0)
return -x;
else
return x;
}
LinkList deleRestSame(LinkList &L)
{
LNode *locate = L->link;
LNode *pre,*p;
while(locate)
{
pre = locate;
p = pre->link;
while(p)
{
if(fabs(locate->data) == fabs(p->data))
{
pre->link = p->link;
free(p);
p = pre->link;
}else{
pre = p;
p = p->link;
}
}
locate = locate->link;
}
return L;
}
bool printList(LinkList L)
{
LNode *p = L->link;
while(p)
{
printf("%d ",p->data);
p = p->link;
}
printf("\n");
return true;
}
void main()
{
LinkList L;
tailInsertList(L);
deleRestSame(L);
printList(L);
}
方法二:空间换时间
#include<stdio.h>
#include<stdlib.h>
typedef int ElemType;
typedef struct LNode{
ElemType data;
struct LNode *link;
}LNode,*LinkList;
LinkList tailInsertList(LinkList &L)
{
ElemType x;
L = (LinkList)malloc(sizeof(LNode));
LNode *r=L;
scanf("%d",&x);
while(x!=9999)
{
LNode *s = (LNode*)malloc(sizeof(LNode));
s->data = x;
r->link = s;
r = s;
scanf("%d",&x);
}
r->link = NULL;
return L;
}
LinkList deleRestSame(LinkList &L,int n)
{
LNode *p=L;
LNode *r;
int *q,m;
q = (int*)malloc(sizeof(int)*(n+1));
for(int i=0;i<n+1;++i)
*(q+i) = 0;
while(p->link)
{
m = p->link->data>0?p->link->data:-p->link->data;
if(*(q+m)==0){
*(q+m) = 1;
p = p->link;
}else{
r = p->link;
p->link = r->link;
free(r);
}
}
free(q);
return L;
}
bool printList(LinkList L)
{
LNode *p = L->link;
while(p)
{
printf("%d ",p->data);
p = p->link;
}
printf("\n");
return true;
}
void main()
{
LinkList L;
tailInsertList(L);
deleRestSame(L,5);
printList(L);
}
删除其余(取绝对值)相同的结点
最新推荐文章于 2024-08-20 23:46:37 发布