Creating Node:
Traversing Function:
Insert at the beginning:
Insert at the particular index:
Insert at the End:
Linked List Complete Insertion Program:
struct Node
{
int data;
struct Node *next;
};
void Traversed_link_list(struct Node *ptr)
{
while (ptr != NULL)
{
cout << "Element: " << ptr->data << endl;
ptr = ptr->next;
}
}struct Node *insert_at_beginning(struct Node *head, int data)
{
struct Node *ptr;
ptr = new Node(); // Memory allocation for new Node
ptr->next = head;
ptr->data = data;
head = ptr;
return head;
}
struct Node *insert_at_Index(struct Node *head, int data, int index)
{
struct Node *ptr;
ptr = new Node(); // Memory allocation for new Node
struct Node *p = head;
int i = 0;
while (i != index - 1)
{
p = p->next;
i++;
}
ptr->data = data;
ptr->next = p->next;
p->next = ptr;
return head;
}
struct Node *insert_at_end(struct Node *head, int data)
{
struct Node *ptr;
ptr = new Node(); // Memory allocation for new Node
ptr->data = data;
struct Node *p = head;
while (p->next != NULL)
{
p = p->next;
}
p->next = ptr;
ptr->next = NULL;
return head;
}
#include <iostream>
using namespace std;
struct Node
{
int data;
struct Node *next;
};
void Traversed_link_list(struct Node *ptr)
{
while (ptr != NULL)
{
cout <<"Element: " <<ptr->data << endl;
ptr = ptr->next;
}
}
// Insert at the beginning
struct Node *insert_at_beginning(struct Node *head, int data)
{
struct Node *ptr;
ptr = new Node(); // Memory allocation for new Node
ptr->next = head;
ptr->data = data;
head = ptr;
return head;
}
// Insert at the particular index
struct Node *insert_at_Index(struct Node *head, int data, int index)
{
struct Node *ptr;
ptr = new Node(); // Memory allocation for new Node
struct Node *p = head;
int i = 0;
while (i != index - 1)
{
p = p->next;
i++;
}
ptr->data = data;
ptr->next = p->next;
p->next = ptr;
return head;
}
// Insert at the End
struct Node *insert_at_end(struct Node *head, int data)
{
struct Node *ptr;
ptr = new Node(); // Memory allocation for new Node
ptr->data = data;
struct Node *p = head;
while (p->next != NULL)
{
p = p->next;
}
p->next = ptr;
ptr->next = NULL;
return head;
}
int main()
{
struct Node *head;
struct Node *second;
struct Node *third;
struct Node *fourth;
head = new Node(); // Memory allocation
second = new Node(); // Memory allocation
third = new Node(); // Memory allocation
fourth = new Node(); // Memory allocation
head->data = 23;
head->next = second;
second->data = 45;
second->next = third;
third->data = 45;
third->next = fourth;
fourth->data = 78;
fourth->next = NULL;
cout << "Before Inserting..." << endl;
Traversed_link_list(head);
int ele;
cout << "Enter Element " < < endl;
cin >> ele;
head = insert_at_beginning(head, ele);
cout << "After Inserting element at the Beginning... " << endl;
Traversed_link_list(head);
return 0;
}
Comments
Post a Comment