单链表面试题之从尾到头打印单链表

来源:互联网 发布:淘宝商品没有品牌 编辑:程序博客网 时间:2024/06/02 09:06

逆序打印单链表,就是利用递归的方法将单链表的每个数据都打印出来

其程序为:

void PrintTailToHead(SListNode *pHead)       //从尾到头打印单链表{if (pHead){PrintTailToHead(pHead->next);printf("%d ", pHead->data);}}

测试用例:

void Test4(){SListNode *list = NULL;PushBack(list, 1);PushBack(list, 2);PushBack(list, 3);PushBack(list, 4);PushBack(list, 5);printf("Before:");PrintSList(list);printf("Afert:");PrintTailToHead(list);printf("\n");}

其中的尾插函数:

void PushBack(SListNode *&pHead, DataType x)      //尾插{if (pHead == NULL){pHead = BuyNode(x);}else{SListNode *cur = NULL;cur = pHead;while (cur->next){cur = cur->next;}cur->next = BuyNode(x);}}

打印函数:

void PrintSList(SListNode *pHead)          //打印{SListNode *cur = pHead;while (cur){printf("%d ", cur->data);cur = cur->next;}printf("\n");}

运行结果:

Before:1 2 3 4 5
Afert:5 4 3 2 1

1 0
原创粉丝点击