/* 已知线性表中元素以值递增有序排列,并以单链表作为存储结构
* 设计一个算法,删除表中值相同的多余元素
* 使得操作后表中所用元素值均不同,同时释放被删除的结点空间
*/
#include<stdio.h>
#include<stdlib.h>
#define OK 1
#define ERROR 0
typedef int ElemType;
typedef int Status;
typedef struct Node
{
ElemType data;
struct Node * next;
}Node,*LinkList;
//单链表的初始化
Status InitLinkList(LinkList * L)
{
(*L)=(LinkList)malloc(sizeof(Node));
if((*L)==NULL)
{
printf("内存分配失败!\n");
return 0;
}
(*L)->next=NULL;
return OK;
}
//单链表的建立
Status Create(LinkList * L,int n)
{
LinkList P,Q;
ElemType Elem;
Q=(*L);
printf("请按递增顺序输入元素:\n");
for(int i=0;i<n;i++)
{
P=(LinkList)malloc(sizeof(Node));
scanf("%d",&Elem);
P->data=Elem;
Q->next=P;
Q=P;
}
P->next=NULL;
return OK;
}
//删除结点
Status Delete(LinkList * L,int Location)
{
LinkList Q,P;
int count=0;
int k=Location+1;
Q=(*L);
P=(*L)->next;
while(P->next)
{
Q=Q->next;
P=P->next;
count++;
if(count==Location)
{
Q->next=P->next;
}
}
return OK;
}
//定位删除结点的位置并删除
Status Locate(LinkList * L)
{
LinkList First,Second;
int count=1;
First=(*L)->next;
Second=(*L)->next->next;
while(Second)
{
if(First->data==Second->data)
{
Delete(L,count);
Second=Second->next;
}
else
{
count++;
First=First->next;
Second=Second->next;
}
}
return OK;
}
void Print(LinkList * L)
{
LinkList P;
P=(*L)->next;
while(P)
{
printf("%d ",P->data);
P=P->next;
}
printf("\n");
}
int main()
{
LinkList L;
int Number;
InitLinkList(&L);
printf("请输入元素个数:\n");
scanf("%d",&Number);
Create(&L,Number);
printf("输出链表:\n");
Print(&L);
Locate(&L);
printf("输出去掉相同元素后链表:\n");
Print(&L);
return 0;
}