每天一个小算法(3)----倒序打印链表
这个比较简单,用栈、递归、倒转链表都可以实现,不再过多解释。
代码使用递归实现
1 #include <stdio.h> 2 #include <time.h> 3 #include <stdlib.h> 4 typedef struct Node 5 { 6 int data; 7 Node* next; 8 }Node, *List; 9 10 11 List createList(int num) //随机生成数字,构造链表 12 { 13 List aList = (List)malloc(sizeof(Node)); 14 aList->next = NULL; 15 aList->data = 0; 16 Node* qT = aList; 17 18 // srand((int)time(0)); 19 for ( int i=0; i< num; ++i) 20 { 21 Node* pTN = (Node*)malloc(sizeof(Node)); 22 pTN->data = rand()%100; 23 pTN->next = NULL; 24 qT->next = pTN; 25 qT = pTN; 26 } 27 return aList; 28 } 29 30 void printList(List aList) //正序打印链表 31 { 32 if ( aList == NULL || aList->next == NULL ) 33 return; 34 35 Node* pT = aList->next; 36 printf("element of the list:\n\t"); 37 while( pT != NULL ) 38 { 39 printf("%d ", pT->data); 40 pT = pT->next; 41 } 42 43 printf("\n"); 44 } 45 46 void reversePrintList(List aList) //倒序打印链表 47 { 48 if ( aList == NULL ) 49 return; 50 51 reversePrintList(aList->next); 52 printf("%d ", aList->data); 53 } 54 55 void deleteList(List aList) //删除链表 56 {} 57 58 int main(int argc, char const *argv[]) 59 { 60 srand((int)time(0)); 61 List aList = createList(7); 62 printList(aList); 63 printf("reverse print the list:\n\t"); 64 reversePrintList(aList->next); 65 printf("\n"); 66 67 deleteList(aList); 68 69 return 0; 70 }