【C语言】删除单链表重复结点

#include 
#include 
struct cell {//单链表结点结构体定义
int x;
struct cell* next;
};
struct cell* build(void) {//新建单链表,并将建好的单链表首结点地址返回
struct cell* head, * tmp, * p;
head = tmp = p = NULL;
int n;
head=(struct cell*)malloc(sizeof(struct cell));
head->next=NULL;
tmp=head;
while(head!=NULL){
	scanf("%d",&n);
	if(n==0)break;
	p=(struct cell*)malloc(sizeof(struct cell));
	p->x=n;
	tmp->next=p;
	p->next=NULL;
	tmp=p;
}
if(head->next==NULL){
	free(head);
	head=NULL;
}
return head;//返回单链表头
}
struct cell* del2one(struct cell* head) {//删除重复结点只保留一个,head是单链表首结点指针
struct cell* tmp,*p,*cur;
if(head==NULL)return head;
tmp=p=head->next;
while(p!=NULL){
	tmp=p;
	while(tmp->next!=NULL){
		if(tmp->next->x==p->x){
			cur=tmp->next;
			tmp->next=cur->next;
			free(cur);
		}
		else tmp=tmp->next;
	}
	p=p->next;
}
return head;//返回删除重复结点的单链表头
}
void print(struct cell* head) {//打印整个单链表,head是单链表首结点指针
struct cell* tmp,*p;
tmp=p=head->next;
while(tmp!=NULL){
	printf("%d",tmp->x);
	if(tmp->next!=NULL)printf(" ");
	tmp=tmp->next;
}
}
void release(struct cell* head) {//释放单链表空间,head是单链表首结点指针
struct cell* tmp,*p;
p=tmp=head;
while(tmp!=NULL){
	p=tmp;
	tmp=tmp->next;
	free(p);
}
}
int main(void) {
struct cell* head;
head = build();
head=del2one(head);
if(head!=NULL)
       print(head);
   else
       printf("NULL");
release(head);
}

你可能感兴趣的:(c语言,开发语言)