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

#include <stdio.h>
#include <malloc.h>
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);
}

  • 0
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Polaris北极星少女

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值