In: Computer Science
Part 1- Delete an element from an Array. See the instructions below: -Use the previous Array code provided to you (to demonstrate how to insert elements in an Array). It is an Array with the following details: Size 10 Length 5. Your task is to Delete element on index 4
please use the code below and write in C++ how to delete the 4th element.
#include 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 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; }
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
Part 1:
Code in C++:
#include <iostream>
using namespace std;
int deleteElement(int arr[], int n, int x)
{
// Search x in array
int i;
for (i=0; i<n; i++)
if (arr[i] == arr[x])
break;
// If x found in array
if (i < n)
{
// reduce size of array and move all
// elements on space ahead
n = n - 1;
for (int j=i; j<n; j++)
arr[j] = arr[j+1];
}
return n;
}
/* Driver program to test above function */
int main()
{
int arr[] = {2,3,4,5,6};
int n = sizeof(arr)/sizeof(arr[0]);
int x = 4; //index number 4
cout << "Given array is \n";
for (int i=0; i<n; i++)
cout << arr[i] << " ";
// Delete x from arr[]
n = deleteElement(arr, n, x-1);
cout << "\n\nModified array is \n";
for (int i=0; i<n; i++)
cout << arr[i] << " ";
return 0;
}
Output:
This program has been compiled using online C++ conpiler.
Part 2:
Code in C++:
#include <iostream>
using namespace std;
class Node {
public:
int data;
Node* next;
};
// This function prints contents of linked list
// starting from the given node
void printList(Node* n)
{
cout<<"The linked List is "<< endl;
while (n != NULL) {
cout << n->data << " ";
n = n->next;
}
}
// Driver code
int main()
{
Node* head = NULL;
Node* second = NULL;
Node* third = NULL;
Node* forth = NULL;
Node* fifth = NULL;
// allocate 5 nodes in the heap
head = new Node();
second = new Node();
third = new Node();
forth = new Node();
fifth = new Node();
head->data = 5; // assign data in first node
head->next = second; // Link first node with second
second->data = 6; // assign data to second node
second->next = third;
third->data = 8; // assign data to third node
third->next = forth;
forth->data = 10; // assign data to forth node
forth->next = fifth;
fifth->data = 12; // assign data to fifth node
fifth->next = NULL;
printList(head);
return 0;
}
Output:
This program has been compiled using online C++ conpiler.