Answer to Question #287881 in C++ for Roe

Question #287881

Implement a generic singly linked list class using template class and template functions


Note:


1)Implement the basic operations:insert, delete, search and delete


2)Run test the functions in main


3)No global declarations

1
Expert's answer
2022-01-20T16:18:38-0500


#include <bits/stdc++.h>
using namespace std;



struct Node
{
    int data;
    struct Node* link;
};


struct Node* top;


void push(int data)
{
    
    struct Node* temp;
    temp = new Node();
    if (!temp)
    {
        cout << "\nHeap Overflow";
        exit(1);
    }


    temp->data = data;


    temp->link = top;


    top = temp;
}


int isEmpty()
{
    return top == NULL;
}


int peek()
{
    
    if (!isEmpty())
        return top->data;
    else
        exit(1);
}


void pop()
{
    struct Node* temp;


    if (top == NULL)
    {
        cout << "\nStack Underflow" << endl;
        exit(1);
    }
    else
    {
        
        temp = top;


        top = top->link;
        temp->link = NULL;


        free(temp);
    }
}


void display()
{
    struct Node* temp;


    if (top == NULL)
    {
        cout << "\nStack Underflow";
        exit(1);
    }
    else
    {
        temp = top;
        while (temp != NULL)
        {


            cout << temp->data << "-> ";


            temp = temp->link;
        }
    }
}


int main()
{
    
    push(11);
    push(22);
    push(33);
    push(44);


    display();


    cout << "\nTop element is "
        << peek() << endl;


    pop();
    pop();



    display();


    cout << "\nTop element is "
        << peek() << endl;
        
    return 0;
}


Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

Comments

No comments. Be the first!

Leave a comment