vc++ 6.0 堆棧
To implement a stack using a linked list, basically we need to implement the push() and pop() operations of a stack using linked list.
要使用鏈接列表實現堆棧 ,基本上,我們需要使用鏈接列表實現堆棧的push()和pop()操作。
Example:
例:
Input numbers: 1,3,5,8,4,0
輸入數字:1,3,5,8,4,0
We push the numbers into the stack and whenever it executes a pop() operation, the number is popped out from the stack.
我們將數字壓入堆棧,每執行一次pop()操作,數字就會從堆棧中彈出。
Algorithm:
算法:
To implement the push() operation:
要實現push()操作 :
If the Linked list is empty then create a node and point it as head of that Linked List.
如果“鏈接列表”為空,則創建一個節點并將其指向該“鏈接列表”的頭。
If the Linked List is not empty then create a node with the input number to be pushed and make it head of the Linked List.
如果“鏈接列表”不為空,則創建一個帶有要推送的輸入編號的節點,并使它成為“鏈接列表”的頭。
To implement The pop() operation
實現pop()操作
If the Linked List is already empty then do nothing. Output that empty stack.
如果“鏈接列表”已經為空,則什么也不做。 輸出該空堆棧。
If the Linked List is not empty then delete the node from head.
如果“鏈接列表”不為空,則從頭刪除該節點。
C++ implementation:
C ++實現:
#include<bits/stdc++.h>
using namespace std;
struct node{
int data;
node* next;
};
//Create a new node
struct node* create_node(int x){
struct node* temp= new node;
temp->data=x;
temp->next=NULL;
return temp;
}
//Enter the node into the linked list
void push(node** head,int x){
struct node* store=create_node(x);
if(*head==NULL){
*head =store;
return;
}
struct node* temp=*head;
//add the number in the front of the linked list
store->next=temp;
*head=store;
}
//pop from the stack
void pop(node** head){
if(*head==NULL)
return;
struct node* temp=(*head)->next;
*head=temp; //delete from the front
}
void print(node* head){
struct node* temp=head;
while(temp){
cout<<temp->data<<" ";
temp=temp->next;
}
}
int main()
{
struct node* l=NULL;
push(&l,1);
push(&l,2);
push(&l,3);
push(&l,4);
push(&l,5);
push(&l,6);
cout<<"Before the pop operation"<<endl;
print(l);
pop(&l);
pop(&l);
cout<<"\nAfter the pop operation"<<endl;
print(l);
return 0;
}
Output
輸出量
Before the pop operation
6 5 4 3 2 1
After the pop operation
4 3 2 1
翻譯自: https://www.includehelp.com/cpp-programs/implement-stack-using-linked-list-in-cpp.aspx
vc++ 6.0 堆棧