vc++ 6.0 堆栈_在C ++中使用链接列表实现堆栈

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()操作,数字就会从堆栈中弹出。

stack using linked list

Algorithm:

算法:

To implement the push() operation:

要实现push()操作

  1. If the Linked list is empty then create a node and point it as head of that Linked List.

    如果“链接列表”为空,则创建一个节点并将其指向该“链接列表”的头。

  2. 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()操作

  1. If the Linked List is already empty then do nothing. Output that empty stack.

    如果“链接列表”已经为空,则什么也不做。 输出该空堆栈。

  2. 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 堆栈

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值