数据结构 七

重写链表

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

typedef struct Data
{
	int id;
	char name[15];
}Data;
typedef struct Node
{
	struct Data data;
	struct Node *next;
}Node;
//创建链表并初始化
struct Node *CreateHead( Node **head)
{
	if(NULL==head)
		return;
	
	*head=(Node *)malloc(sizeof(Node) );
	if(NULL==*head)
		return;
	
	(*head)->next=NULL;
	(*head)->data.id=0;
	(*head)->data.name[0]='\0';
	
	return *head;
}
//头插
int Insert_tail(Node *head,Data data)
{
	Node *newnode=(Node *)malloc(sizeof(Node) );
	
	newnode->data.id=data.id;
	
	strcpy(newnode->data.name,data.name);
	
	while(head->next!=NULL)
	{
		head=head->next;
	}
	head->next=newnode;
	
	newnode->next=NULL;
	
	return 1;
}
//打印函数
void  print(Data *data)
{
	printf("id=%d,name=%s\n",data->id,data->name);
}
//打印所有数据
void Dispaly(Node *head)
{
	while(head->next!=NULL)
	{
		print((&head->next->data));
		head=head->next;
	}
}
//删除
int Delete(Node *head,Data data)
{
	
	while(head->next!=NULL)
	{
		if(head->next->data.id==data.id)
		{
			Node *temp=head->next;
			head->next=temp->next;
			
			free(temp);
			temp=NULL;
			
			//return -1;
		}
		head=head->next;
	}
	return 1;
}


//链表长度
int Length(Node *head)
{
	int i;
	while(head->next!=NULL)
	{
		i++;
		head=head->next;
	}
	return i;
}
int main()
{
	struct Node *head;
	struct Data data1={10,"ggjj"};//给数据结构值
	struct Data data2={11,"ggjj"};
	struct Data data3={12,"ggjj"};
	struct Data data4={13,"ggjj"};
	int i;
	
	CreateHead(&head);
	
	Insert_tail(head,data1);
	Insert_tail(head,data2);
	Insert_tail(head,data3);
	Insert_tail(head,data4);
	i=Length(head);
	printf("长度是%d\n",i);
	Dispaly(head);
	
	printf("\n");
	
	Delete(head,data1);
	Dispaly(head);
	
	
	
	return 0;
}

总结
之前学了链表同时也用链表写了一些程序,但是这次重写链表我觉得我对链表还是不懂,就连第一步链表初始化都不会写了。我想我对链表的理解还是不够,我还得努力去学他。

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值