实现代码使用两个指针,p用来遍历链表,q每次指向p的下一个位置,若p->data==q->data则删除q
#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; }



