从尾到头打印链表
题目描述:输入一个链表,从尾到头打印链表每个节点的值。
算法:
1 #include<stdio.h> 2 #include<stdlib.h> 3 #include<malloc.h> 4 5 typedef struct ListNode{ 6 int data; 7 struct ListNode *next; 8 }ListNode; 9 10 void Print(ListNode *pHead){ //递归实现逆序打印链表节点 11 if(pHead != NULL){ 12 if(pHead->next != NULL){ 13 Print(pHead->next); 14 } 15 printf("%d\n", pHead->data); 16 } 17 } 18 19 20 ListNode *CreateList() //创建链表 21 { 22 int num; 23 ListNode *pHead = NULL; 24 ListNode *p = NULL; 25 26 do 27 { 28 scanf("%d",&num); 29 if(num != -1) //当输入的节点为-1时链表结束 30 { 31 ListNode* pNew = (ListNode*)malloc(sizeof(ListNode)); 32 if(pNew == NULL) 33 exit(EXIT_FAILURE); 34 pNew->data = num; 35 pNew->next = NULL; 36 37 if(pHead == NULL) 38 { 39 pHead = pNew; 40 p = pHead; 41 } 42 else 43 { 44 p->next = pNew; 45 p = p->next; 46 } 47 } 48 }while(num != -1); 49 return pHead; 50 } 51 52 53 int main(){ 54 ListNode *h = CreateList(); 55 Print(h); 56 return 0; 57 }