单向链表

单向链表

在这里插入图片描述

  • 初始化时因为要修改指针的值,所以要用指针的指针.
  • l=(Node*)malloc(sizeof(Node));l为指针的引用
  • free(NULL)没有任何事情发生
#include<stdio.h>
#include<stdlib.h>
typedef struct Node{
	int data;
	struct Node* next;
}Node,*List;
//初始化 
bool initList(List &l){
	l=(Node*)malloc(sizeof(Node));
	if(l==NULL){
		return false;
	}
	l->next=NULL;
	return true;
}
//2插入一个数
bool listInsert(List l,int n,int e){
	if(n<1){
		return false;
	}
	Node* p=l;
	int i=0;
	while(p!=NULL&&i<n-1){
		p=p->next;
		i++;					/*忘了i++了,导致只能插入到第一个,不能插入到其他位置,因为若n不为1则while无限循环至p=NULL*/ 
	}
	if(p==NULL){
		return false;
	}
	Node* s=(Node*)malloc(sizeof(Node));
	s->next=p->next;
	p->next=s;
	s->data=e;
	return true; 
}
//3按值删除集合中的元素
bool listDelete(List l,int e){
	Node* p=l->next;
	Node* q=l;
	while(p!=NULL&&p->data!=e){
		p=p->next;
		q=q->next;
	}
	if(p==NULL){
		return false;
	}
	q->next=p->next;
	free(p);
} 
//4按值在集合中查找
int searchByElem(List l,int e){
	Node *p=l->next;
	int i=1;
	while(p!=NULL&&p->data!=e){
		p=p->next;
		i++;
	}	
	if(p==NULL){
		return -1;
	}
	//printf("值为%d的元素在第%d的位置上\n",e,i);
	return i;
}
//5清空集合
void clearList(List l){
	Node *p=l->next;
	Node *q=l;
	while(p!=NULL){
		q=p;
		p=p->next;						//free(NULL)没有任何事发生 
		free(q);
	}
	l->next=NULL;
	printf("清空集合成功!\n");	
}
//6求两个集合的交集
void getIntersection(List a,List b){
	Node *p=a->next;
	printf("交集:\n");
	while(p!=NULL){
		if(searchByElem(b,p->data)!=-1){
			printf("%d\n",p->data);
		}
		p=p->next;
	}
}
//7并集 
void getUnion(List a,List b){
	printf("并集:\n");
	//打印a 
	Node *p=a->next;
	while(p!=NULL){
		printf("%d\n",p->data);
		p=p->next;
	}
	//打印a中没有b中有的
	p=b->next;
	while(p!=NULL){
		if(searchByElem(a,p->data)==-1){
			printf("%d\n",p->data);
		}
		p=p->next;
	} 
}
//8差集
void getSubs(List a,List b){
	printf("差集:\n");
	Node *p=a->next;
	while(p!=NULL){
		if(searchByElem(b,p->data)==-1){
			printf("%d\n",p->data);
		}
		p=p->next;
	}
} 
//9输出集合
void printList(List l){
	Node *p=l->next;
	printf("**********\nList:\n");
	int i=0;
	while(p!=NULL){
		printf("data[%d]:%d\n",i++,p->data);
		p=p->next;
	}
	printf("**********\n");
} 
int main(){
	List l;
	initList(l);
	printList(l);
	listInsert(l,1,10);
	listInsert(l,2,20);
	listInsert(l,3,30);
	listDelete(l,20);
	
	List li;
	initList(li);
	listInsert(li,1,11);
	listInsert(li,1,21);
	listInsert(li,1,20);
	listInsert(li,1,30);
	
	printList(l);
	printList(li);
	getIntersection(l,li);
	getUnion(l,li);
	getSubs(l,li);
	return 0;
} 
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值