链表\链表基础应用

 文章有点长,不过每个分块都有标注啦~

之后的分文件虽然不难,但是一块一块讲起来有点麻烦

大家可以去参考一下文档(文档还是很详细的)

链表实际上就是指针的运用

可以想象成一节一节的火车,通过钩子连接,而这个钩子就是指针 

#include
#include
#include
#include

//定义结构体
typedef struct Node
{
	int data;
	struct Node *next;
}Node;

//函数声明
Node *Create();
void Print(Node *head);
void Release(Node *head);
Node *Delete(Node *head,int num);
int que(char str[]);
Node *Insert(Node *head,int num);

int main()
{
	//初始化
	Node *head;
	char c;
	int ret1,ret2;
	char str[15]={0};

	//调用函数
	head=Create();
	Print(head);

	//删除数据(提示)
	strcpy(str,"delete?");
	ret1=que(str);
	//删除数据
	int bs;
	if(ret1==1)
	{
		printf("请输入想要删除的数据:");
		scanf("%d",&bs);
		Delete(head,bs);
		printf("删除后的");
	}
	else
		printf("已保持数据完整\n");
	Print(head);

	//插入数据(提示)
	int ret3;
	strcpy(str,"insert?");
	ret3=que(str);
	//插入数据
	int ins;
	if(ret3==1)
	{
		printf("请输入想要插入的数据:");
		scanf("%d",&ins);
		Insert(head,ins);
		printf("插入后的");
	}
	else
		printf("已保持数据完整\n");
	Print(head);

	//释放内存(提示)
	strcpy(str,"release?");
	ret2=que(str);
	//释放内存
	if(ret2==1)
		{
			printf("yes,you're right~\n");
			Release(head);
		}
		else
		{
			printf("不好意思,你莫得选择。\n");
			Release(head);
		}

	system("pause");
	return 0;
}

//函数定义
//生成链表
Node *Create()
{
	//链表初始化
	Node *head,*tail,*p;
	int num;
	head=tail=NULL;

	//输入数据个数
	int count=0;

	//输入数据
	printf("请输入数据(以-1结尾)");
	scanf("%d",&num);

	//逐个读取并建立链表
	while(num!=-1)
	{
		p=(Node*)malloc(sizeof(Node));
		p->data=num;
		p->next=NULL;
		if(head==NULL)
			head=p;
		else
			tail->next=p;
		tail=p;
		scanf("%d",&num);
	}
	return head;	
}

//输出
void Print(Node *head)
{
	Node *p;
	p=head;
	if(head==NULL)
		printf("链表为空!\n");
	else
	{
		printf("链表如下:\n");
		while(p!=NULL)
		{
			printf("%d ",p->data);
			p=p->next;
		}
	}
	printf("\n");
}

//释放
void Release(Node *head)
{
	Node *p1,*p2;
	p1=head;
	while(p1!=NULL)
	{
		p2=p1;
		p1=p1->next;
		free(p2);	//一个一个释放
	}
	printf("链表释放成功!\n");
}

//删除
Node *Delete(Node *head,int num)
{
	Node *p1,*p2;

	if(head==NULL)
	{
		printf("链表为空!\n");
		return head;
	}

	p1=head;
	
	//循环查找
	while(p1->next && p1->data!=num)
	{
		p2=p1;
		p1=p1->next;
	}

	//找到
	if(p1->data==num)
	{
		if(p1==head)
			head=p1->next;
		else
			p2->next=p1->next;	//指针指向的交换
		free(p1);	//p1被替代后即可释放
		printf("删除成功!\n");	//反馈
	}
	//没找到
	else
		printf("该数据不存在!\n");
	return head;
}

//提示
int que(char str[])
{
	int ret=0;
	char c;
	do{
		printf("%s\n",str);
		fflush(stdin);	//缓存区还有别的东西,吞掉
		scanf("%c",&c);
		getchar();	//吞掉回车
	}while(c!='y' && c!='Y' && c!='n' && c!='N');
	if(c=='y' || c=='Y')
		ret=1;
	return ret;
}

//插入
Node *Insert(Node *head,int num)
{
	//初始化
	Node *p,*p1,*p2;

	//把待插入的数据做成一节
	p=(Node*)malloc(sizeof(Node));
	p->data=num;
	p->next=NULL;

	//确定插入位置
	while(p1 && p->data>p1->data)
	{
		p2=p1;
		p1=p1->next;
	}

	//插入
	if(p1==head)
		head=p;
	else
		p2->next=p;
	p->next=p1;
	printf("数据插入成功!\n");
	return head;
}

你可能感兴趣的:(C语言进阶,c语言)