Q:

Implement Stack using Linked List in C++

belongs to collection: C++ programs on various topics

0

cImplement Stack using Linked List in C++

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

C++ implementation:

#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

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

C++ programs on various topics

This question belongs to these collections

Similar questions


need a help?


find thousands of online teachers now
Delete the middle node of a Linked List in C++... >>
<< C++ program to check if number is power of 2 using...