链表中重复元素的删除 发表于 2017-10-08 | 分类于 C++ 1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677#include <stdio.h>#include <stdlib.h>#include <iostream>using namespace std;struct node{ int data; struct node *next;};struct node *creat(int n){ struct node *head,*p; head=(struct node *)malloc(sizeof(struct node)); head->next=NULL; for(int i=0;i<n;i++) { p=(struct node *)malloc(sizeof(struct node )); scanf("%d",&p->data); p->next=head->next; head->next=p; } return head;};void show (struct node *head){ struct node *p; p=head->next; while(p) { if(!p->next) { printf("%d\n",p->data); } else { printf("%d ",p->data); } p=p->next; }}void del(struct node *&head,int &n){ struct node *q,*p,*t; p=head->next; while(p) { t=q; //上t在p的位置上 q=p->next; //让q代表遍历的指针 while(q) { if(q->data==p->data) //当查找到重复的元素的时候 { t->next=p->next; n--; p=p->next; } else { t=t->next; p=p->next; } } q=q->next; }}int main(){ struct node *head; int n; scanf("%d",&n); head=creat(n); printf("%d\n",n); show(head); del(head,n); printf("%d\n",n); show(head);}