Download as pdf or txt
Download as pdf or txt
You are on page 1of 4

Lecture Notes on Linked List

Insert a node at the beginning


Program to Insert a Node at the Head/Beginning of a Linked List
// Program
#include <stdlib.h>
#include <stdio.h>
// Declare the Node
struct Node
{
int data;
struct Node* next;
};
struct Node* head;
// Insert the node a the beginning of a linked list
void insert(int data)
{
struct Node* temp = (struct Node*)malloc(sizeof(struct Node));
temp->data = data;
temp->next = head;
head = temp;
}

void print()
{
struct Node* temp = head;
while(temp!=NULL)
{
printf("%d",temp->data);
temp = temp->next;
printf("\n");
}
}
int main()
{
head = NULL;
insert(4);
insert(5);
insert(6);
print();
}
Linked-List : Insert Node at Middle Position in Singly Linked List
#include "stdio.h"
#include "stdlib.h"
struct Node
{
int data;
struct Node* next;
};
struct Node* head;
void Insert(int data, int n)
{
struct Node* temp1 = (struct Node*)malloc(sizeof(struct Node));
temp1->data=data;
temp1->next = NULL;
if (n == 1) // if we enter in the 1st position
{
temp1->next = head;
head=temp1;
return;
}
Node* temp2=head;
for (int i = 0; i < n-2; i++)
{
temp2 = temp2->next;
}
temp1->next = temp2->next;
temp2->next = temp1;
}

void Print()
{
Node* temp = head;
while (temp != NULL) {
printf("%d", temp->data);
temp = temp->next;
}
printf("\n");
}

void main()
{
head = NULL;
printf("program begins..\n");
Insert(2,1);
Insert(5, 2);
Insert(3, 3); // Insert(4, 1);
Print();
}
Delete a node from a linked list:
#include "stdio.h"
#include "stdlib.h"
struct Node
{
int data;
struct Node* next;
};
struct Node* head;

void Insert(int x)
{
printf(" Adding node %d \n", x);
struct Node* temp = (Node*) malloc(sizeof (struct Node));
struct Node* temp2 = (Node*) malloc(sizeof (struct Node));
temp -> data = x;
temp -> next = NULL;
if (head == NULL)
{
head = temp;
return;
}
temp2 = head;
while (temp2->next != NULL)
{
temp2 = temp2->next;
}
temp2 -> next = temp;
}
void delete_node(int n)
{
struct Node* temp1 = (Node*) malloc(sizeof (struct Node));
temp1 = head; /correction point, add this statement in your code/
if (n==1)
{
head = temp1 -> next;
free (temp1);
return;
}
for (int i=0; i <n-2; i++)
{
temp1 = temp1 -> next;
}
struct Node* temp2 = (Node*) malloc (sizeof (struct Node));
temp2 = temp1 ->next;
temp1 ->next = temp2 -> next;
free (temp2);
}
void Printlist()
{
struct Node * printNode = head;
printf ("list elements are ");
while (printNode != NULL)
{
printf(" %d ", printNode -> data);
printNode = printNode -> next;
}
printf("\n");
}
int main()
{
head = NULL; //empty list int n;
Insert (2);
Insert (4);
Insert (6);
Insert (5);
Printlist();
printf("enter a number to delete node ");
scanf("%d", &n);
delete_node(n);
Printlist();
}

You might also like