单链表的建立,把a~z 26个字母插入到链表中,并且倒叙,还要打印

发布时间:2024年01月19日

?单链表的建立,把a~z 26个字母插入到链表中,并且倒叙,还要打印

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

typedef int DataType;
typedef struct ListNode
{
	DataType data;
	struct ListNode* next;
}ListNode;
ListNode* BuyListNode(DataType x)
{
	ListNode* newnode = (ListNode*)malloc(sizeof(ListNode));
	if(newnode == NULL)
	{
		printf("malloc error\n");
		exit(-1);
	}
	newnode->data = x;
	newnode->next = NULL;
}
void ListNodePrint(ListNode* phead)
{
	assert(phead);
	ListNode* cur = phead;
	while(cur)
	{
		printf("%c->",(char)cur->data);
		cur = cur->next;
	}
	printf("NULL");
}
void pushback(ListNode** phead,DataType x)
{
	assert(phead);
	ListNode* newnode = BuyListNode(x);
	if((*phead) == NULL)
	{
		*phead = newnode;
	}
	else if((*phead)->next == NULL)
	{
		(*phead)->next = newnode;
	}
	else
	{
		ListNode* tail = *phead;
		while(tail->next != NULL)
		{
			tail = tail->next;
		}
		tail->next = newnode;
	}
}
//逆序打印(递归)
void ReversePrint(ListNode *phead)
{
	if (phead == NULL)  //递归出口
	{
		return;
	}
	ReversePrint(phead->next);
	printf("%c->",(char)(phead->data));
}
int main()
{
	/*单链表的建立,把a~z 26个字母插入到链表中,并且倒叙,还要打印*/
	ListNode* LN = NULL;//空链表
	int i = 0;
	for(i = 0;i<26;i++)
	{
		pushback(&LN,i+'a');
	}
//	ListNodePrint(LN);
//	printf("\n");
	//倒叙打印
	printf("**********************\n");
	ReversePrint(LN);
	printf("NULL\n");
	return 0;
}
zhibin@zhibin-virtual-machine:~/code_Learning/code_2024_1_19/lesson$ vim test.c
zhibin@zhibin-virtual-machine:~/code_Learning/code_2024_1_19/lesson$ gcc -o test test.c
zhibin@zhibin-virtual-machine:~/code_Learning/code_2024_1_19/lesson$ 
zhibin@zhibin-virtual-machine:~/code_Learning/code_2024_1_19/lesson$ ./test
**********************
z->y->x->w->v->u->t->s->r->q->p->o->n->m->l->k->j->i->h->g->f->e->d->c->b->a->NULL
zhibin@zhibin-virtual-machine:~/code_Learning/code_2024_1_19/lesson$ 

文章来源:https://blog.csdn.net/weixin_57604904/article/details/135690340
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。