【数据结构】typedef struct 和 struct在链表中的应用

(1) struct{ int x; int y; }test1; 
定义了 结构 test1,
test1.x 和 test1.y 可以在语句里用了。

(2) struct test {int x; int y; }test1; 
定义了 结构 test1,
test1.x 和 test1.y 可以在语句里用了。
与 1 比,1里面省写 了 test

(3) 
typedef struct test 
{int x; int y;  }text1,text2; 
只说了 这种结构 的(类型)别名 叫 text1 或叫 text2

真正在语句里用,还要写:
text1 hwh;
然后好用 hwh.x, hwh.y

或写 text2 hwh1;
然后好用 hwh.x, hwh.y

(4)typedef struct {int x; int y; }test1;
同 (3)一样,真正在语句里用,还要 写:
test1 hwh;
才能用 hwh.x 和 hwh.y
 
(5)超高端用法
typedef struct list *list_p; //首先定义了一个结构体list,在这里要把struct list看成是一体了,继续分析
//在这里,list_p是一个结构体指针,struct list *就等同于list_p,这样做是可以在下面互相替换
//在定义结构list之前,定义了一个指向该结构的指针list_p,C语言允许定义指向不存在的类型的指针。
typedef struct list{
char a[3];
list_p link;//结构体自引用,这句话等同于struct list * link;。link是一个指向结构体的的指针
};
//在定义了结构list之后,就可以建立一个新表,用list_p ptr = Null; 完成。
list_p ptr = Null; //存在一个名为ptr的新表ptr包含表的起始地址
ptr = (list_p) malloc(sizeof(list));  // 
//e->name 等同与(*e).name//e是指针
strcpy(ptr->a, "bat");
ptr->link = NULL;
 
 
-----
完整代码:
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
main()
{
	typedef struct list_node *list_pointer;
	typedef struct list_node
	{
		char data[4];
		list_pointer link;
	};
	list_pointer ptr = NULL;
	ptr = (list_pointer)malloc(sizeof(list_node));
	strcpy(ptr->data, "bat");
	ptr->link = NULL;
	printf("%s\n",ptr->data);
}
-----
#include<stdio.h>
#include<stdlib.h>
#define IS_Empty(ptr) (!(ptr))
#define IS_FULL(ptr) (!(ptr))

typedef struct list_node *list_pointer;
typedef struct list_node
{
	int data;
	list_pointer link;
};
list_pointer ptr = NULL;

list_pointer create()
{
	list_pointer first = NULL, second = NULL;
	first = (list_pointer)malloc(sizeof(list_node));
	second = (list_pointer)malloc(sizeof(list_node));
	first->data = 10;
	first->link = second;
	second->data = 20;
	second->link = NULL;
	return first;
}

void insert(list_pointer *ptr, list_pointer node)
{
	list_pointer temp;
	temp = (list_pointer) malloc (sizeof(list_node));
	if(IS_FULL(temp))
	{
		fprintf(stderr,"The memory is full.\n");
		exit(1);
	}
	temp->data = 50;
	if(*ptr)
	{
		temp->link = node->link;
		node->link =temp;
	}
	else
	{
		temp->link =NULL;
		*ptr = temp;
	}
}

void delete_node(list_pointer *ptr, list_pointer trail, list_pointer node)
{
	if(trail)
	{
		trail->link = node->link;
	}
	else
	{
		*ptr = (*ptr)->link;
	}
	free(node);
}
void print_list(list_pointer ptr)
{
	printf("Thw list contains:\n");
	for(; ptr; ptr=ptr->link)
	{
		printf("%4d",ptr->data);
	}
	printf("\n");
}
void main()
{
	ptr = create();
	insert(&ptr, ptr->link);
	printf("After insert--------------------------\n");
	print_list(ptr);
	delete_node(&ptr, ptr, ptr->link);
	printf("After delete--------------------------\n");
	print_list(ptr);	
}



评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值