In: Computer Science
Part 2- - Create and display a singly Linked List with 5 elements (see below)
Node* head
Node*second
Node*third
Node*forth
Node*fifth
2-Assign the data 5, 6, 8, 10, 12 to each node 3-Display the output
GIVEN CODE:
#include <studio.h>
struct Array { int A[10]; int size; int length; };
void Display(struct Array arr)
{
int i; printf("\nElements are\n");
for(i=0;ilengthsize) arr->A[arr->length++]=x;
}
void Insert(struct Array *arr,int index,int x)
{
int i;
if(index>=0 && index <=arr->length)
{
for(i=arr->length;i>index;i--)
arr->A[i]=arr->A[i-1]; arr->A[index]=x; arr->length++;
}
}
int main()
{
struct Array arr1={{2,3,4,5,6},10,5};
Append(&arr1,10);
Insert(&arr1,0,12);
Display(arr1);
return 0;
}
Linked List Question (Part -2)code:
#include<iostream>
using namespace std;
class node{
public:
int data;
node* next;
node(int x){
this->data=x;
this->next=NULL;
}
};
int main(){
node* head=NULL;
head= new node(5);
head->next= new node(6);
head->next->next= new node(8);
head->next->next->next= new node(10);
head->next->next->next->next= new node(12);
cout<<"the linked list is: ";
node* temp=head;
while(temp){
cout<<temp->data<<" ";
temp=temp->next;
}
}
Screenshot and Output:
2)
Array Question (Modified as per need. Kindly comment if you find any mistake. I'll code it for you)
Code:
#include <stdio.h>
struct Array {
int A[10];
int size;
int length;
};
void Display(struct Array arr){
int i;
printf("\nElements are\n");
for(i=0;i<arr.length;i++)
printf("%d ", arr.A[i]);
}
void Append(struct Array *arr, int x){
int i;
arr->A[arr->length++]=x;
}
void Insert(struct Array *arr,int index,int x){
int i;
if(index>=0 && index <=arr->length){
for(i=arr->length-1;i>index;i--)
arr->A[i]=arr->A[i-1];
arr->A[index]=x;
arr->length++;
}
}
int main(){
struct Array arr1={{2,3,4,5,6},10,5};
Display(arr1);
Append(&arr1,10);
Display(arr1);
Insert(&arr1,0,12);
Display(arr1);
return 0;
}
Code Screenshot and Output:
Please comment in case of doubts or queries.
Kindly upvote if you found this helpful :)