Professional Documents
Culture Documents
Enrollment #: 01-235171-074
Objective
This lab session is aimed at enhancing the algorithmic development skills of the students by
writing small utility functions for linked lists. In addition, the students will also implement the
‘Stack’ class using a linked list.
Exercises 1
Implement the following exercises.
A stack can be implemented using a linked list. The first node can serve as the ‘top’ of Stack and
‘push’ and ‘pop’ operations can be implemented by adding and removing nodes at the head of
the linked list. Implement the Stack class using a linked list and provide all the standard
member functions.
CODE:
class Node
{
public:
Node* next;
int data;
};
class stack{
public:
void push(int value);
int pop();
void Display();
int Top();
};
Create an organized linked list in ascending order i.e., all the entries should be added in the list
in ascending order. An illustration of the working of the program is presetned in the following.
List list ;
list.insert (5) ; //5 list.insert (2) ;
//2 5 list.insert (7) ; //2 5 7
list.insert (3) ; //2 3 5 7
CODE:
head=ptr;
}
else
{
Node* temp;
Node* prevtemp;
temp=head;
prevtemp=temp;
while(ptr->data>temp->data)
{
prevtemp=temp;
temp=temp->next;
if(temp==NULL)
break;
}
if(temp==head)
{
ptr->next=head;
head=ptr;
}
Exercise 4
Write the following C++ functions to realize the indicated functionality on a singly linked list of
integers.
• A function which adds first and second record and places the result in the third record.
Likewise, third and fourth records are added to place the result in the fifth record. There
are N numbers of records in the linked list.
• A function that deletes the first half of the linked list nodes. You are required to first
determine the total number of linked list nodes and then delete the first part of the
linked list.
Code:
DeleteEven:
void Node::deleteEvenNode()
{
if(head==NULL)
{
cout<<"List Empty";
}
else
{
int count=0;
Node* temp=head;
Node* prevptr;
Node* ptr;
void Node::deleteHalf()
{
Node *temp=head;
Node *ptr=head,*prevptr;
int count=1,n,i=0;
while(temp->next!= NULL)
{
temp = temp->next;
count++;
}
n=count/2;
while(i<n)
{
prevptr=ptr;
ptr=ptr->next;
delete prevptr;
i++;
}
head=ptr;
}
Implement the given exercises and get them checked by your instructor. If you are unable to
complete the tasks in the lab session, deposit this journal alongwith your programs (printed
or handwritten) before the start of the next lab session.
2. Exercise 2
3. Exercise 3
4. Exercise 4