第2章 线性表的链式表示
综合应用题 第23题
![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/ff35386b1837293bee7d6ff6c9c19973.png)
#include <stdio.h>
#include <stdlib.h>
#include <iostream>
using namespace std;
typedef int ElemType;
typedef struct node {
ElemType data;
struct node *link;
}LNode, *LinkList;
LinkList LinkListInit() {
LNode *L;
L = (LNode *)malloc(sizeof(LNode));
if (L == NULL) {
cout<<"申请内存空间失败\n";
exit(0);
}
L->link = NULL;
return L;
}
LinkList LinkListCreatT(ElemType *a, int n) {
LNode *L;
L = LinkListInit();
LNode *r;
r = L;
LNode *p;
for (int i = 0; i < n; i++){
p = (LNode *)malloc(sizeof(LNode));
if (p == NULL) {
cout<<"申请内存空间失败\n";
exit(0);
}
p->data = a[i];
p->link = r->link;
r->link = p;
r = p;
}
return L;
}
void deleteSame(LinkList &L,int n)
{
int *a;
a=(int*)malloc(sizeof(int)*(n+1));
for(int i=0;i<n+1;i++)
{
a[i]=0;
}
LNode *p=L->link,*pre=L,*q;
while(p)
{
int flag=p->data>0?p->data:-p->data;
if(a[flag]==0)
{
a[flag]=1;
pre=p;
p=p->link;
}
else
{
q=p->link;
pre->link=q;
delete p;
p=q;
}
}
}
int main() {
LinkList list, start;
int m,n;
cout<<"请输入m:";
cin>>m;
cout<<"请输入n:";
cin>>n;
int array1[m];
cout<<"输入单链表的数据:(小于等于n)"<<endl;
for(int i=0;i<m;i++)
{
cin>>array1[i];
}
list=LinkListCreatT(array1,m);
for (start = list->link; start != NULL; start = start->link) {
cout<<start->data<<" ";
}
cout<<endl;
deleteSame(list,n);
for (start = list->link; start != NULL; start = start->link) {
cout<<start->data<<" ";
}
cout<<endl;
return 0;
}
![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/170a78bd750476ee6b328acb0dfc7d66.png)