删除有序链表中重复元素

时间:2025-03-03 14:31:33
#include <> #include <> #include<> typedef int Elemtype; typedef struct LNode { Elemtype data; struct LNode *next; } LNode,*LinkList; LinkList List_TailInsert(LinkList L) { int x; L=(LinkList)malloc(sizeof(LinkList));//创建头节点 L->next=NULL; LNode *r=L,*s; scanf("%d",&x); while(x!=9999) { s=(LNode*)malloc(sizeof(LNode*)); s->data=x; r->next=s; r=s; scanf("%d",&x); } r->next=NULL; return L; } LinkList List_HeadInsert(LinkList L) { LNode *s; int x; L=(LinkList)malloc(sizeof(LNode)); L->next=NULL; scanf("%d",&x); while(x!=9999) { s=(LNode*)malloc(sizeof(LNode)); s->data=x; s->next=L->next; L->next=s; scanf("%d",&x); } return L; } void PrintLinkList(LinkList L) { printf("打印链表\n"); LNode *r=L->next; while(r!=NULL) { printf("%d--->",r->data); r=r->next; } printf("\n"); } LinkList Del_Same(LinkList L) { LNode *p=L->next,*q; //两个指针不断移动 if(p==NULL)return; while(p->next!=NULL) { q=p->next; if(p->data==q->data) { p->next=q->next; free(q); } else { p=p->next; } } return L; } int main() { LinkList L;//头指针,创建链表 printf("创建链表,输入链表的值 9999表示结束!\n"); L=List_TailInsert(L); PrintLinkList(L); printf("删除重复元素\n"); LinkList B; B=Del_Same(L); PrintLinkList(L); return 0; }