In: Computer Science
In C++
Write the definition for following methods of List data structure.
5. pushFront – The function appends an element in the list at the front. The operation increases the number of elements in the list by one.
6. pushback - The function appends an element in the list at the end. The operation increases the number of elements in the list by one.
7.popFront - The function returns and then removes an element in the list from the front. The operation decreases the number of elements in the list by one.
8.popBack - - The function returns and then removes an element in the list from the end. The operation decreases the number of elements in the list by one.
#include<iostream>
#include<bits/stdc++.h>
using namespace std;
struct Node
{
int val;
struct Node *next;
Node(int data)
{
val=data;
next=NULL;
}
};
void pushFront(Node *&head, int data)
{
if(head==NULL)
{
head=new Node(data);
return ;
}
struct Node *temp;
temp = new Node(data);
temp->next = head;
head = temp;
}
void pushback(Node *&head, int data)
{
if(head==NULL)
{
head = new Node(data);
return ;
}
struct Node *cur=head;
while(cur->next!=NULL)
{
cur = cur->next;
}
cur->next = new Node(data);
}
void popFront(struct Node *&head)
{
if(head==NULL)
return ;
head=head->next;
}
void popBack(struct Node *&head)
{
if(head==NULL)
return ;
struct Node *cur=head,*pre=NULL;
while(cur->next!=NULL)
{
pre=cur;
cur=cur->next;
}
if(pre)
pre->next=NULL;
else
head=NULL;
}
void display(struct Node *head)
{
if(head==NULL)
return ;
while(head!=NULL)
{
cout<<head->val<<" ";
head=head->next;
}
cout<<endl;
}
int main()
{
struct Node *head=NULL;
pushFront(head, 5); // here it append 5 at the beginning in list.
display(head); // 5 is printed
pushback(head, 3); // here it append 3 at end of list
display(head); // 5 3 is printed
popFront(head); // it pop 5 from the list
display(head); // 3 is printed
popBack(head); // it pop the element from the end of list
display(head); // nothing is printed.
}
// This code is executable if any problem you will face to understand the code you can comment.