zoukankan      html  css  js  c++  java
  • 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 
  • 相关阅读:
    【k8s】deploy-progressDeadlineSeconds
    【k8s】deploy-paused
    【k8s】deploy-rollback
    【k8s】deploy-rollout
    【k8s】deploy-pod-template-hash
    【k8s】deploy-rs
    【k8s】deploy-metadata
    垂直居中总结
    linux操作系统的知识点复盘
    JMETER接口测试学习知识点复盘
  • 原文地址:https://www.cnblogs.com/soyo/p/8734314.html
Copyright © 2011-2022 走看看