#include<stdio.h>
#include<malloc.h>
typedef struct LNode
{
int data;
struct LNode *next;
}*LinkList;
LinkList Create_List_Tail(int length)
{//建立链表
LNode *L,*s,*r; //L指向头结点,r指向尾结点,s指向新添加结点
L=(LinkList)malloc(sizeof(LNode));
L->next =NULL;//头结点L->data不存东西
r=L;
for(int i=0;i<length;++i)
{
s=(LinkList)malloc(sizeof(LNode));
scanf("%d",&s->data);
r->next =s;
r =s;
}
r->next =NULL;
return L; //返回链表
}
void PrintList(LinkList L)
{
LNode* pNode = L->next ;
if(!pNode)
printf("空表!\n");
while(pNode)
{
printf("%d ", pNode->data);
pNode = pNode->next;
}
printf("\n");
}
LNode *Find(LinkList L,int data)
{
LNode *p=L->next ;
while(p&&p->data !=data)
p=p->next ;
if(!p)
printf("不存在!\n");
return p;
}
void DeleteNode(LinkList L,LNode *p)
{
if(!L||!L->next!=NULL)
return;
// 要删除的结点不是尾结点
if(p->next!=NULL)
{
LNode *q=p->next;
p->data=q->data;
p->next=q->next;
free(q);
}
// 链表只有一个结点,删除头结点(也是尾结点)
else if(L->next==p)
{
free(p);
L->next=NULL;
}
// 链表中有多个结点,删除尾结点
else
{
LNode *q=L->next;
while(q->next!=p)
q=q->next;
q->next=NULL;
free(p);
}
}
void main()
{
LinkList L;
LNode *p;
int length,data;
printf("请输入元素个数:");
scanf("%d",&length);
L=Create_List_Tail(length);
printf("打印链表:\n");
PrintList(L);
printf("请输入要删除的元素值:\n");
scanf("%d",&data);
p=Find(L,data);
DeleteNode(L,p);
printf("删除指定元素后的链表:\n");
PrintList(L);
}
#include<stdio.h>
#include<malloc.h>
typedef struct LNode
{
int data;
struct LNode *next;
}*LinkList;
LinkList Create_List_Tail(int length)
{//建立链表
LNode *L,*s,*r; //L指向头结点,r指向尾结点,s指向新添加结点
L=(LinkList)malloc(sizeof(LNode));
L->next =NULL;//头结点L->data不存东西
r=L;
for(int i=0;i<length;++i)
{
s=(LinkList)malloc(sizeof(LNode));
scanf("%d",&s->data);
r->next =s;
r =s;
}
r->next =NULL;
return L; //返回链表
}
void PrintList(LinkList L)
{
LNode* pNode = L->next ;
if(!pNode)
printf("空表!\n");
while(pNode)
{
printf("%d ", pNode->data);
pNode = pNode->next;
}
printf("\n");
}
void DeleteDuplication(LinkList &L)
{
if(!L||!L->next)
return;
LNode* p1 = L;
LNode* p2 = L->next ;
while(p2 != NULL)
{
LNode *p3 = p2->next;
if(p3 != NULL && p3->data == p2->data)
{
int value = p2->data;
while(p2 != NULL && p2->data == value)
{
p3 = p2->next;
free(p2);
p2 = p3;
}
p1->next =p3;
p2 = p3;
}
else
{
p1 = p2;
p2 = p3 ;
}
}
}
void main()
{
LinkList L;
LNode *p;
int length,data;
printf("输入链表长度:");
scanf("%d",&length);
L=Create_List_Tail(length);
printf("原始链表为:: \n");
PrintList(L);
DeleteDuplication(L);
printf("删除重复元素后链表为:: \n");
PrintList(L);
}