Question
Question
class Node
{
public:
int data;
Node *next;
};
// assign data
new_node->data = data;
int main(){
insertFront(&head,4);
insertFront(&head,5);
insertFront(&head,6);
insertFront(&head,7);
insertFront(&head,8);
insertFront(&head,9);
printList(head);
return 0;
}
Output:
Question #2:
Write a code in c++ to perform insertion at end in linked list.
#include<iostream>
using namespace std;
class Node
{
public:
int data;
Node *next;
};
freshNode->data = data;
// since this will be the last node so it will point to NULL
freshNode->next = NULL;
//need this if there is no node present in linked list at all
if(*head==NULL)
{
*head = freshNode;
cout << freshNode->data << " inserted" << endl;
return;
}
int main()
{
insertEnd(&head,7);
insertEnd(&head,8);
insertEnd(&head,9);
insertEnd(&head,10);
display(head);
return 0;
}
Output:
Question #3:
Insertion at specific point:
#include<iostream>
using namespace std;
class Node {
public:
int data;
Node* next;
};
// if the linked list is empty, make the new node the head
if (*head_ref == NULL) {
*head_ref = new_node;
return;
}
// else, traverse to the specified position and insert the new node
Node* temp = *head_ref;
for (int i = 0; i < position - 1; i++) {
temp = temp->next;
}
new_node->next = temp->next;
temp->next = new_node;
}
int main() {
Node* head = NULL;
return 0;
}
Output:
Question # 4
Deletion at start
#include<iostream>
using namespace std;
class node{
public:
int data;
node*next;
node(int d){
data=d;
node*next=NULL;
}
};
void insertAtFirstNode (node*&head, int data){
node*n= new node(data);
n->next= head;
head=n;
}
void print(node*head){
while(head!=NULL){
cout<<head->data<<"->";
head=head->next;
}
cout<<endl;
}
void deleteAtFirst(node*&head){
if(head==NULL){
return;
}
node*temp=head;
head= head->next;
delete temp;
return;
}
int main(){
node*head= NULL;
insertAtFirstNode(head,1);
insertAtFirstNode(head,2);
insertAtFirstNode(head,3);
insertAtFirstNode(head,4);
deleteAtFirst(head);
print(head);
}
Question #5
Deletion at end
#include<iostream>
using namespace std;
class Node
{
public:
int data;
Node *next;
};
newNode->data = data;
newNode->next = *head;
int main ()
{
Node *head = NULL;
display (head);
deleteEnd (&head);
deleteEnd (&head);
deleteEnd (&head);
display (head);
return 0;
}
Output: