从尾到头打印链表,这里的链表一般都是指单链表,因为如果是双向链表就没什么可以打印的了。
方法一(利用栈)
因为链表是头到尾的去遍历的,如果要从尾到头的去遍历,那么很容易想到栈这种数据结构来解决这个问题。
栈这种数据结构,如下图堆积起来的书,只能从顶部堆积(即push操作)或者拿走(即pop操作)书籍。
代码如下:
typedef struct listnode{
int key;
struct listnode *next;
}listnode;
void print_linkedlist_reverse(listnode *head)
{
std::stack <listnode *> nodes;
listnode *p = head;
while (p != NULL){
nodes.push(p);
p = p->next;
}
while ( !nodes.empty() ){
p = nodes.top();
printf("%d\t", p->key);
nodes.pop();
}
}
注意:若链表很长,函数层级调用很深,可能会导致函数调用栈溢出。