58.从尾到头输出链表。
题目:输入一个链表的头结点,从尾到头反过来输出每个结点的值。
思路:题不难,提供几种思路
1.使用栈的先进后出特性实现,遍历链表元素依次入栈,再出栈即可达到目的
2.使用数组先暂存顺序遍历的结果,再对数组反向遍历即可。
3.递归,也就是这里采用的方法。
C++代码:
#include "stdafx.h"
#include<ctime>
#include<iostream>
namespace MS100P_58
{
void reversePrintList(node* p)
{
if (p == NULL) return;
reversePrintList(p->next);
cout << p->data << ' ';
}
void test()
{
node *head = createList(20);
printList(head);
reversePrintList(head->next);
cout << endl;
deleteList(head);
}
}
int _tmain(int argc, _TCHAR* argv[])
{
MS100P_58::test();
return 0;
}
运行结果:
附测试代码中用到的创建,打印,删除链表的函数
struct node
{
int data;
node* next;
};
node* createList(int len) //创建链表
{
node* head = new node();
node* pCurrent = head;
srand(time(0));
for (int i = 0; i < len; i++)
{
pCurrent->next = new node();
pCurrent = pCurrent->next;
pCurrent->data = rand() % 100;
}
pCurrent->next = NULL;
return head;
}
void deleteList(node *p)
{
node*q;
while (p != NULL)
{
q = p;
p = p->next;
delete q;
}
}
void printList(node * head) //打印输出链表内容
{
node* p = head->next;
while (NULL != p)
{
cout << p->data << ' ';
p = p->next;
}
cout << endl;
}