题目:输入一个链表的头结点,从尾到头反过来打印出每个节点的值。
说实话,我最开始的思路是,定义一个辅助数组,将这个链表的值依次存入到数组中去,压根就没打算用栈这个数据结构的。我感觉两个效率差不多吧。有想法的通知麻烦指出来。
算法实现
#include <iostream>
#include<stack>
using namespace std;
struct Node
{
int val;
Node * next;
};
struct List
{
Node * head;
int size;
};
void initList(List * list)
{
list->head = new Node();
list->size = 0;
}
void addList(List * list, int array[], int len)
{
int i;
Node * p = list->head;
for (i = 0; i < len; i++)
{
Node * temp = new Node();
temp->next = NULL;
temp->val = array[i];
p->next = temp;
p = temp;
list->size++;
}
}
//倒序输出
void DaoXuShuChu(List list)
{
Node * pHead = list.head;
if (pHead->next == NULL && list.size == 0)
{
cout << "链表为空" << endl;
return;
}
int length = list.size;
int i = length;
int * pValue = new int[length];
Node * p = pHead->next; //让p指向链表第一个元素
while (p != NULL)
{
pValue[--i] = p->val;
p = p->next;
}
for (int j = 0; j < length; j++)
cout << pValue[j] << endl;
}
//倒序输出1
void DaoXuShuChu1(List list)
{
Node * pHead = list.head;
if (pHead->next == NULL && list.size==0)
{
cout << "链表为空" << endl;
return;
}
stack<int> ss;
Node * p = pHead->next; //让p指向链表第一个元素
while (p!=NULL)
{
ss.push(p->val);
p = p->next;
}
//返回在堆栈中元素数目
int n = ss.size();
for (int i = 0; i < n; i++)
{
cout << ss.top() << endl;
ss.pop();
}
}
//倒序输出2
void DaoXuShuChu2(List list)
{
Node * pHead = list.head;
if (pHead->next == NULL && list.size == 0)
{
cout << "链表为空" << endl;
return;
}
//知识改变了栈结构中存储的数据类型而已,根本就算不上另外一种。
stack<Node*> ss;
Node * p = pHead->next; //让p指向链表第一个元素
while (p != NULL)
{
ss.push(p);
p = p->next;
}
//返回在堆栈中元素数目
int n = ss.size();
for (int i = 0; i < n; i++)
{
cout << (ss.top())->val << endl;
ss.pop();
}
}
//倒序输出3
//采用递归也可以实现。我就没写了,有兴趣的人可以试试
int main()
{
List list;
initList(&list);
int array[10] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
addList(&list, array, 10);
DaoXuShuChu(list);
return 0;
}