C++实现从尾到头打印链表(不改变链表结构)

/*
 * 从尾到头打印链表.cpp
 *
 *  Created on: 2018年4月7日
 *      Author: soyo
 */
#include<iostream>
#include<stack>
using namespace std;
struct node
{
    int data;
    node * next;
};
node * create_head(node *p,int v)
{
    p=new node;
    p->data=v;
    p->next=NULL;
    return p;
}
node * add_list(node*head,int n)
{
    node *p,*p1;
    p=head;
    p1=new node;
    p1->data=n;
    p1->next=NULL;
    while(p->next!=NULL)
        p=p->next;
    p->next=p1;
    return head;
}
void println(node *head)
{
    if(head==NULL)
        return;
    while(head!=NULL)
    {
        cout<<head->data<<" ";
        head=head->next;
    }
    cout<<endl;
}
void ReversePrint(node *head)
{
    if(head==NULL)
        return;
    stack<node*>s;
    node *p;
    while(head!=NULL)
    {
        s.push(head);
        head=head->next;
    }
    while(!s.empty())
    {
        p=s.top();
        cout<<p->data<<" ";
        s.pop();
    }

}
int main()
{
   node *p,*head;
   int data=5;
   head=create_head(p,data);
   int a[]={2,4,6,7,8,9};
   for(int i=0;i<sizeof(a)/sizeof(int);i++)
   {
       head=add_list(head,a[i]);
   }
   println(head);
   cout<<"利用栈从尾到头打印链表"<<endl;
   ReversePrint(head);

}

 结果:

5 2 4 6 7 8 9 
利用栈从尾到头打印链表
9 8 7 6 4 2 5 
原文地址:https://www.cnblogs.com/soyo/p/8734314.html