zoukankan      html  css  js  c++  java
  • 数据结构 栈

    栈是一种重要的数据结构,具有后进先出的特点,对栈的操作可以采取没有头结点和有头结点两种方式,但是如果没有头结点,出栈会有点麻烦,顾采取了有头结点的方式。


    1.入栈。

    因为先进先出的特性,所以入栈其实就是把新结点作为了新栈的第一个数据结点(不一定是头结点,头结点有可能作为开始标志,本文就是),然后用新结点的next指针指向原来栈的第一个数据结点。

    2.出栈。

    出栈就是把头结点的next指针指向第二个数据结点,把第一个数据结点脱离栈后,把它释放。


    代码如下:

    #include<iostream>
    #include<malloc.h>


    using namespace std;


    struct Lines{

    int order;
    char data;

    Lines* next;
    };


    void Menu();
    Lines* newNode();
    bool is_Empty(Lines* head);
    void enter(Lines* head);
    void out(Lines* head);
    void Show(Lines* head);


    int main(int argc,char** argv){

    Lines* head = newNode();
    int select;

    while(true){

    Menu();
    cin >> select;

    switch(select){

    case 1:
    enter(head);
    break;
    case 2:
    out(head);
    break;
    case 3:
    Show(head);
    break;
    case 0:
    exit(1);
    break;
    default:
    cout << "输入无效,请重新输入" << endl;
    break;
    }
    }
    }


    void Menu(){

    system("cls");
    cout << "1.入栈" << endl;
    cout << "2.出栈" << endl;
    cout << "3.遍厉栈" << endl;
    cout << "0.退出" << endl;
    cout << endl << "请输入功能代叫进行下一步操作" << endl; 
    }


    void Show(Lines* head){

    system("cls");

    while(head->next != NULL){

    cout << head->next->order << " " << head->next->data << endl;
    head = head->next;
    }

    system("pause");
    }


    Lines* newNode(){

    Lines* node = NULL;
    node = (Lines*)malloc(sizeof(Lines));
    node->next = NULL;
    node->data = '0';
    node->order = 0;

    return node;
    }


    void enter(Lines* head){

    system("cls");

    Lines* node = newNode();
    cout << "请输入您的编号" << endl;
    cin >> node->order;
    cout << "请输入您的等级" << endl;
    cin >> node->data;

    node->next = head->next;
    head->next = node;

    cout << "入栈成功" << endl;

    system("pause");
    }


    void out(Lines* head){

    system("cls");

    Lines* node = newNode();
    node->next = head->next;

    if(!is_Empty(head)){

    head->next = head->next->next;
    free(node);

    }else{

    cout << "栈内不存在任何元素" << endl;
    }

    cout << "出栈成功" << endl;

    system("pause");
    }


    bool is_Empty(Lines* head){

    if(head->next == NULL){

    return true;

    }else{

    return false;
    }
    }

  • 相关阅读:
    Excel表导入数据库时带小数点的数据会变成科学计数样式的解决方法
    C# 具有合计行的DataGridViewNiceDataGridView1.0
    nginx 【使用echo调试】【地址复写】
    ts 【申明文件】
    createreactapp 【引入ui框架样式,全局样式被处理成模块化样式处理方法】
    node 【node服务器搭建1:安转node 和pm2】
    http 【前后端缓存】【nginx配合缓存】
    nginx 【匹配规则】【开启gzip压缩】
    nginx【nginx配置】
    react 【useMome、useCallback原理详解】
  • 原文地址:https://www.cnblogs.com/viplanyue/p/12700706.html
Copyright © 2011-2022 走看看