?单链表的建立,把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$