数据结构 栈

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


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;
}
}

猜你喜欢

转载自blog.csdn.net/itlanyue/article/details/80605078