054 DSA Assignment 2
054 DSA Assignment 2
Submitted To:
Sir Sarwar Khan
Submitted By:
Muhammad Jahanzaib
20101001-054
3rd Semester Yellow
BS Software Engineering
Topic: - Array and link list
Array: -
#include <iostream>
using namespace std;
class Array{
private:
int arr[5];
int count=0;
public:
void insertAtBeginning(){
if(count<5){
for(int i=count;i>0;i--){
arr[i]=arr[i-1];
}
cout << "\nEnter a number : ";
cin >> arr[0];
count++;
}
else{
cout << "\nArray is full !!!";
}
1
}
void DeleteAtBeginning(){
for(int i=0;i<count;i++){
arr[i]=arr[i+1];
}
count--;
}
void DeleteAtEnd(){
arr[count]=0;
count--;
}
void traverse(){
for(int i=0;i<count;i++){
cout << arr[i] << " ";
}
}
};
int main() {
Array a1;
int ch;
cout << "\n1. Insert at beginning";
cout << "\n2. Delete at beginning";
cout << "\n3. Delete at end";
cout << "\n4. Traverse";
while(1){
cout << "\nEnter your choice : ";
2
cin >> ch;
switch(ch){
case 1:
a1.insertAtBeginning();
break;
case 2:
a1.DeleteAtBeginning();
break;
case 3:
a1.DeleteAtEnd();
break;
case 4:
a1.traverse();
break;
default:
cout << "\nWrong choice try again !!!";
break;
}
}
return 0;
}
3
Output: -
4
Link list: -
#include <iostream>
using namespace std;
struct node{
int data;
node* next;
};
class linklist{
private:
node* head;
node* tail;
public:
linklist(){
head=NULL;
tail=NULL;
}
void insertAtBeginning(){
node* temp=new node;
cout << "\nEnter data : ";
cin >> temp->data;
temp->next=NULL;
if(head==NULL){
head=temp;
5
tail=temp;
}
else{
temp->next=head;
head=temp;
}
}
void traverse(){
node *temp=head;
while(temp!=NULL){
cout << temp->data << " ";
temp=temp->next;
}
}
void DeleteAtBeginning(){
node* current=head;
head=head->next;
delete current;
cout << "First element has been deleted";
}
void DeleteAtEnd(){
node* current=tail;
node* temp=head;
while(temp!=NULL){
if(temp->next==tail){
break;
}
6
temp=temp->next;
}
tail=temp;
delete current;
tail->next=NULL;
cout << "\nLast element has been deleted";
}
};
int main() {
linklist l1;
int ch;
cout << "\n1.Insert at beginning";
cout << "\n2.Traverse";
cout << "\n3.Delete at beginning";
cout << "\n4.Delete at end";
while(1){
cout << "\n\nEnter your choice : ";
cin >> ch;
switch(ch){
case 1:
l1.insertAtBeginning();
break;
case 2:
l1.traverse();
break;
case 3:
7
l1.DeleteAtBeginning();
break;
case 4:
l1.DeleteAtEnd();
break;
default:
cout << "\nWrong choice try again !!!";
break;
}
}
return 0;
}
Output: -
8
Figure 4 Delete at beginning and end