Insert at Beginning and last of Linked list
#include<stdio.h>
#include<stdlib.h>
struct Node
{
int data;
struct Node *next;
};
int size=0;
void insertatbegin (struct Node **head, int data)
{
struct Node *newNode = (struct Node *) malloc (sizeof (struct Node));
newNode->data = data;
newNode->next = *head;
//changing the new head to this freshly entered node
*head = newNode;
}
//function to insert after nth node
void insertatposition (int pos, int data, struct Node **head)
{
struct Node *newNode = (struct Node *) malloc (sizeof (struct Node));
newNode->data = data;
newNode->next = NULL;
// Can't insert if position to insert is greater than size of Linked List
// can insert after negative pos
if (pos < 0 || pos > size)
printf ("Invalid position to insert\n");
// inserting first node
else if (pos == 0)
{
newNode->next = *head;
*head = newNode;
}
else
{
// temp used to traverse the Linked List
struct Node *temp = *head;
// traverse till the nth node
while (--pos)
temp = temp->next;
// assign newNode's next to nth node's next
newNode->next = temp->next;
// assign nth node's next to this new node
temp->next = newNode;
size++;
}
}
void insertatLast (struct Node **head, int data)
{
struct Node *newNode = (struct Node *) malloc (sizeof (struct Node));
newNode->data = data;
newNode->next = NULL;
if (*head == NULL)
{
*head = newNode;
return;
}
struct Node *temp = *head;
while (temp->next != NULL)
temp = temp->next;
temp->next = newNode;
size++;
}
void display (struct Node *node1)
{
while (node1 != NULL)
{
printf ("%d ", node1->data);
node1 = node1->next;
}
printf ("\n");
}
int main ()
{
struct Node *head = NULL;
struct Node *node2 = NULL;
struct Node *node3 = NULL;
struct Node *node4 = NULL;
// allocate 3 nodes in the list
head = (struct Node *) malloc (sizeof (struct Node));
node2 = (struct Node *) malloc (sizeof (struct Node));
node3 = (struct Node *) malloc (sizeof (struct Node));
node4 = (struct Node *) malloc (sizeof (struct Node));
head->data = 15;
head->next = node2;
size++;
node2->data = 10;
node2->next = node3;
size++;
node3->data = 12;
node3->next = node4;
size++;
node4->data = 3;
node4->next = NULL;
size++;
printf ("Linklist : ");
display (head);
printf ("\nAfter Inserting Element at the beginning of list\n");
insertatbegin (&head, 25);
printf ("\nLinklist : ");
display (head);
printf ("\nAfter Inserting Element at the position of list\n");
insertatposition (4,20,&head);
printf ("\nLinklist : ");
display (head);
printf ("\nAfter Inserting Element at the last of list\n");
insertatLast (&head, 14);
printf ("\nLinklist : ");
display (head);
return 0;
}