Lab 1 Data Structure
Lab 1 Data Structure
Lab 1 Data Structure
Objective: To learn about types of data structure and mainly the concept of single
linked list.
LAB ASSESSMENT:
Data presentation
Experimental results
Conclusion
Date: Signature:
LAB# 01
DATA STRUCTURE
Lab Task # 1:
Make a function with name add link. Whenever you call this
function in the main, it will create a new node containing data.
SOURCE CODE:
#include<iostream>
using namespace std;
struct node
{
int data;
node *next;
};
class list
{
private:
node *head;
public:
//constructor to intialize
list()
{
head = NULL;
}
// make function add fuction to call this function in main
void add_link(int d)
{
node *temp,*ptr;
if(head==NULL)
{
head = new node;
head->data=d;
head->next=NULL;
}
else
{
ptr=head;
while(ptr->next!=NULL)ptr=ptr->next;
temp = new node;
temp->data=d;
temp->next=NULL;
ptr->next=temp;
}
}
//function to display value
void show()
{
node *temp;
temp = head;
cout<<"The nodes containing data is as follow:"<<endl;
while(temp!=NULL)
{
cout<<temp->data<<" ";
temp = temp->next;
}
}
};
//main function
int main()
{
list l;
l.add_link(10);
l.add_link(20);
l.add_link(30);
l.add_link(12);
l.show();
cout<<endl;
}
Screen shot of program
OUTPUT:
TASK # 2:
Make a function which deletes node from your linked list.
SOURCE CODE:
#include<iostream>
using namespace std;
struct node
{
int data;
node *next;
};
class list
{
private:
node *head;
public:
list()
{
head = NULL;
}
void add(int d)
{
node *temp,*ptr;
if(head==NULL)
{
head = new node;
head->data=d;
head->next=NULL;
}
else
{
ptr=head;
while(ptr->next!=NULL)ptr=ptr->next;
temp = new node;
temp->data=d;
temp->next=NULL;
ptr->next=temp;
}
}
void del(int v)
{
node *temp, *pre;
temp = head;
if(temp->data==v)
{
head = temp->next;
delete temp;
cout<<endl<<v<<"has been deleted."<<endl;
return;
}
pre = temp;
while(temp!=NULL)
{
if(temp->data==v)
{
pre->next=temp->next;
delete temp;
cout<<"/nValue deleted."<<endl;
return;
}
pre = temp;
temp = temp->next;
}
cout<<endl<<v
}
void display()
{
node *temp;
temp = head;
cout<<"The list is as follow:"<<endl;
while(temp!=NULL)
{
cout<<temp->data<<" ";
temp=temp->next;
}
}
};
int main()
{
list l;
l.add(12);
l.add(13);
l.add(14);
l.add(15);
l.display();
cout<<endl;
l.del(12);
l.display();
}
SCREEN SHOTS OF PROGRAM:
OUTPUT:
TASK #3
Write a function to display all the data of your linked list
sequentially.
SOURCE CODE: