C语言链表实现。

主攻C语言教程已经接近尾声,越发激起了学习数据结构的兴趣。学习数据结构不能没有语言功底,要不然各种错误不知如何调试,使用语言也不是十分自然。这两样应该是相得益彰的,学好一种语言,灵活运用,像说话一样,然后掌握技巧。

在数据结构中 链表是非常重要的。下面是对联表的实现以及基本的操作函数。还有一些细节归纳。

typedef char DATA;                         
struct linked_list
{
	DATA d;
	struct linked_list *next;
};
typedef struct linked_list ELEMENT;
typedef ELEMENT *LINK;

//递归方式生成链表
LINK string_to_list(char s[])
{
	LINK head;
	if(s[0] == '\0')
		return NULL;
	else
	{
		head = (LINK)malloc(sizeof(ELEMENT));
		head->d = s[0];
		head->next = string_to_list(s + 1);          //s是一个指针通过指针进行移位分别指向字符串的每一个字符。
		return head;
	}
}
//迭代方式生成链表
LINK s_to_l(char s[])
{
	LINK head = NULL, tail;
	int i;
	if(s[0] != '\0')
	{
		head = (LINK)malloc(sizeof(ELEMENT));
		head->d = s[0];
		tail = head;
		for(i = 1; s[i] != '\0'; ++i )// add to tail
		{
			tail -> next = (LINK)malloc(sizeof(ELEMENT));
			tail = tail -> next;
			tail -> d = s[i];
		}
		tail -> next = NULL; 
	}
	return head;
}
//对联表进行计数//递归方法
int count(LINK head)
{
	if(head == NULL)
		return 0;
	else
	{
		return (1 + count(head -> next));
	}
}
//对链表进行计数 迭代方法
int count_list(LINK head)
{
	int cnt = 0;
	for(; head != NULL ; head  = head -> next)
		++cnt;
	return cnt;
}
//递归方法输出链表所有元素。
void print_list(LINK head)
{
	if(head == NULL)
		printf("NULL");
	else{
		printf("%c --> ",head -> d);
		print_list(head->next);
	}
}
///用递归方法连接两个链表
void concatenate(LINK a, LINK b)
{
	assert( a != NULL);
	if(a -> next == NULL)
		a ->next = b;
	else
		concatenate(a -> next,b);
}
//递归允许我们在便利量表a时候,避免使用任何辅助指针。一般而言,自引用的字符链表,使递归方法显得十分自然。这些递归形式基本如下
/*
void generic_recursion(LINK  head)
{
	if(head == NULL)
		do the base one
	else
		do the general case and recur with 
	generic_recursion(head -> next);
}
*/
void insert(LINK p1,LINK p2,LINK q)
{
	assert( p1 -> next == p2);
	p1->next = q;
	q ->next = p2;
}
int main(void)
{
	LINK h;
	h = string_to_list("ABC");
	printf("The resulting list is \n");
	print_list(h);
	printf("\n This list has %d elements.\n",count(h));
	return 0;
}
有了链表就可以实现堆栈实现队列,(当然用数组也可以,各有各的好处);


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值