Program to create, insert, delete and display operations on singly linked list in java

Linked List Operations: Traverse, Insert and Delete

In this tutorial, you will learn different operations on a linked list. Also, you will find implementation of linked list operations in C/C++, Python and Java.

There are various linked list operations that allow us to perform different actions on linked lists. For example, the insertion operation adds a new element to the linked list.

Here's a list of basic linked list operations that we will cover in this article.

  • Traversal - access each element of the linked list
  • Insertion - adds a new element to the linked list
  • Deletion - removes the existing elements
  • Search - find a node in the linked list
  • Sort - sort the nodes of the linked list

Before you learn about linked list operations in detail, make sure to know about Linked List first.

Things to Remember about Linked List

  • head points to the first node of the linked list
  • next pointer of the last node is NULL, so if the next current node is NULL, we have reached the end of the linked list.

In all of the examples, we will assume that the linked list has three nodes 1 --->2 --->3 with node structure as below:

struct node { int data; struct node *next; };

A Linked List is a linear data structure that consists of two parts: one is the data part and the other is the address part. In this article, all the common operations of a singly linked list is discussed in one menu-driven program.

Operations to be performed:

  • createList(): To create the list with ‘n’ number of nodes initially as defined by the user.
  • traverse(): To see the contents of the linked list, it is necessary to traverse the given linked list. The given traverse() function traverses and prints the content of the linked list.
  • insertAtFront(): This function simply inserts an element at the front/beginning of the linked list.
  • insertAtEnd(): This function inserts an element at the end of the linked list.
  • insertAtPosition(): This function inserts an element at a specified position in the linked list.
  • deleteFirst(): This function simply deletes an element from the front/beginning of the linked list.
  • deleteEnd(): This function simply deletes an element from the end of the linked list.
  • deletePosition(): This function deletes an element from a specified position in the linked list.
  • maximum(): This function finds the maximum element in a linked list.
  • mean(): This function finds the mean of the elements in a linked list.
  • sort(): This function sort the given linked list in ascending order.
  • reverseLL(): This function reverses the given linked list.

Below is the implementation of the above operations:




// C program for the all operations in
// the Singly Linked List
#include
#include
// Linked List Node
struct node {
int info;
struct node* link;
};
struct node* start = NULL;
// Function to create list with n nodes initially
void createList()
{
if (start == NULL) {
int n;
printf("\nEnter the number of nodes: ");
scanf("%d", &n);
if (n != 0) {
int data;
struct node* newnode;
struct node* temp;
newnode = malloc(sizeof(struct node));
start = newnode;
temp = start;
printf("\nEnter number to"
" be inserted : ");
scanf("%d", &data);
start->info = data;
for (int i = 2; i <= n; i++) {
newnode = malloc(sizeof(struct node));
temp->link = newnode;
printf("\nEnter number to"
" be inserted : ");
scanf("%d", &data);
newnode->info = data;
temp = temp->link;
}
}
printf("\nThe list is created\n");
}
else
printf("\nThe list is already created\n");
}
// Function to traverse the linked list
void traverse()
{
struct node* temp;
// List is empty
if (start == NULL)
printf("\nList is empty\n");
// Else print the LL
else {
temp = start;
while (temp != NULL) {
printf("Data = %d\n", temp->info);
temp = temp->link;
}
}
}
// Function to insert at the front
// of the linked list
void insertAtFront()
{
int data;
struct node* temp;
temp = malloc(sizeof(struct node));
printf("\nEnter number to"
" be inserted : ");
scanf("%d", &data);
temp->info = data;
// Pointer of temp will be
// assigned to start
temp->link = start;
start = temp;
}
// Function to insert at the end of
// the linked list
void insertAtEnd()
{
int data;
struct node *temp, *head;
temp = malloc(sizeof(struct node));
// Enter the number
printf("\nEnter number to"
" be inserted : ");
scanf("%d", &data);
// Changes links
temp->link = 0;
temp->info = data;
head = start;
while (head->link != NULL) {
head = head->link;
}
head->link = temp;
}
// Function to insert at any specified
// position in the linked list
void insertAtPosition()
{
struct node *temp, *newnode;
int pos, data, i = 1;
newnode = malloc(sizeof(struct node));
// Enter the position and data
printf("\nEnter position and data :");
scanf("%d %d", &pos, &data);
// Change Links
temp = start;
newnode->info = data;
newnode->link = 0;
while (i < pos - 1) {
temp = temp->link;
i++;
}
newnode->link = temp->link;
temp->link = newnode;
}
// Function to delete from the front
// of the linked list
void deleteFirst()
{
struct node* temp;
if (start == NULL)
printf("\nList is empty\n");
else {
temp = start;
start = start->link;
free(temp);
}
}
// Function to delete from the end
// of the linked list
void deleteEnd()
{
struct node *temp, *prevnode;
if (start == NULL)
printf("\nList is Empty\n");
else {
temp = start;
while (temp->link != 0) {
prevnode = temp;
temp = temp->link;
}
free(temp);
prevnode->link = 0;
}
}
// Function to delete from any specified
// position from the linked list
void deletePosition()
{
struct node *temp, *position;
int i = 1, pos;
// If LL is empty
if (start == NULL)
printf("\nList is empty\n");
// Otherwise
else {
printf("\nEnter index : ");
// Position to be deleted
scanf("%d", &pos);
position = malloc(sizeof(struct node));
temp = start;
// Traverse till position
while (i < pos - 1) {
temp = temp->link;
i++;
}
// Change Links
position = temp->link;
temp->link = position->link;
// Free memory
free(position);
}
}
// Function to find the maximum element
// in the linked list
void maximum()
{
int a[10];
int i;
struct node* temp;
// If LL is empty
if (start == NULL)
printf("\nList is empty\n");
// Otherwise
else {
temp = start;
int max = temp->info;
// Traverse LL and update the
// maximum element
while (temp != NULL) {
// Update the maximum
// element
if (max < temp->info)
max = temp->info;
temp = temp->link;
}
printf("\nMaximum number "
"is : %d ",
max);
}
}
// Function to find the mean of the
// elements in the linked list
void mean()
{
int a[10];
int i;
struct node* temp;
// If LL is empty
if (start == NULL)
printf("\nList is empty\n");
// Otherwise
else {
temp = start;
// Stores the sum and count of
// element in the LL
int sum = 0, count = 0;
float m;
// Traverse the LL
while (temp != NULL) {
// Update the sum
sum = sum + temp->info;
temp = temp->link;
count++;
}
// Find the mean
m = sum / count;
// Print the mean value
printf("\nMean is %f ", m);
}
}
// Function to sort the linked list
// in ascending order
void sort()
{
struct node* current = start;
struct node* index = NULL;
int temp;
// If LL is empty
if (start == NULL) {
return;
}
// Else
else {
// Traverse the LL
while (current != NULL) {
index = current->link;
// Traverse the LL nestedly
// and find the minimum
// element
while (index != NULL) {
// Swap with it the value
// at current
if (current->info > index->info) {
temp = current->info;
current->info = index->info;
index->info = temp;
}
index = index->link;
}
// Update the current
current = current->link;
}
}
}
// Function to reverse the linked list
void reverseLL()
{
struct node *t1, *t2, *temp;
t1 = t2 = NULL;
// If LL is empty
if (start == NULL)
printf("List is empty\n");
// Else
else {
// Traverse the LL
while (start != NULL) {
// reversing of points
t2 = start->link;
start->link = t1;
t1 = start;
start = t2;
}
start = t1;
// New head Node
temp = start;
printf("Reversed linked "
"list is : ");
// Print the LL
while (temp != NULL) {
printf("%d ", temp->info);
temp = temp->link;
}
}
}
// Driver Code
int main()
{
int choice;
while (1) {
printf("\n\t1 To see list\n");
printf("\t2 For insertion at"
" starting\n");
printf("\t3 For insertion at"
" end\n");
printf("\t4 For insertion at "
"any position\n");
printf("\t5 For deletion of "
"first element\n");
printf("\t6 For deletion of "
"last element\n");
printf("\t7 For deletion of "
"element at any position\n");
printf("\t8 To find maximum among"
" the elements\n");
printf("\t9 To find mean of "
"the elements\n");
printf("\t10 To sort element\n");
printf("\t11 To reverse the "
"linked list\n");
printf("\t12 To exit\n");
printf("\nEnter Choice :\n");
scanf("%d", &choice);
switch (choice) {
case 1:
traverse();
break;
case 2:
insertAtFront();
break;
case 3:
insertAtEnd();
break;
case 4:
insertAtPosition();
break;
case 5:
deleteFirst();
break;
case 6:
deleteEnd();
break;
case 7:
deletePosition();
break;
case 8:
maximum();
break;
case 9:
mean();
break;
case 10:
sort();
break;
case 11:
reverseLL();
break;
case 12:
exit(1);
break;
default:
printf("Incorrect Choice\n");
}
}
return 0;
}




Output:

Menu:

Program to create, insert, delete and display operations on singly linked list in java

Insertion at the starting:

Program to create, insert, delete and display operations on singly linked list in java

Insertion at the end:

Program to create, insert, delete and display operations on singly linked list in java

Insertion at specific position:

Program to create, insert, delete and display operations on singly linked list in java

Print the Linked List:

Program to create, insert, delete and display operations on singly linked list in java

Maximum among Linked List:

Program to create, insert, delete and display operations on singly linked list in java

Sorting the Linked List:

Program to create, insert, delete and display operations on singly linked list in java

Program to create, insert, delete and display operations on singly linked list in java

Reverse the Linked List:

Program to create, insert, delete and display operations on singly linked list in java

Delete the first and last element with choice 5 and 6:

Program to create, insert, delete and display operations on singly linked list in java
Program to create, insert, delete and display operations on singly linked list in java

Program to create, insert, delete and display operations on singly linked list in java

Program to create, insert, delete and display operations on singly linked list in java




Article Tags :
Data Structures
Linked List
Technical Scripter
Delete a Linked List
Linked Lists
Linked-List-Sorting
Menu driven programs
Technical Scripter 2020
Practice Tags :
Data Structures
Linked List

Singly Linked List Example Program in C

Singly Linked List Operations

  • Insert in Linked List
  • Delete node in Linked List based on position
  • Display Nodes in Linked List
  • Count Nodes in Linked List

Singly Linked List Example Program ( Insert, Delete, Display and Count)

/* Singly Linked List Example - All Operations Example Program Using Functions in C*/ /* Data Structure Programs,C Linked List Examples */ /* Singly Linked List Example - Insert,Delete,Display and Count Operations*/ #include #include #include struct node { int value; struct node *next; }; void insert(); void display(); void delete(); int count(); typedef struct node DATA_NODE; DATA_NODE *head_node, *first_node, *temp_node = 0, *prev_node, next_node; int data; int main() { int option = 0; printf("Singly Linked List Example - All Operations\n"); while (option < 5) { printf("\nOptions\n"); printf("1 : Insert into Linked List \n"); printf("2 : Delete from Linked List \n"); printf("3 : Display Linked List\n"); printf("4 : Count Linked List\n"); printf("Others : Exit()\n"); printf("Enter your option:"); scanf("%d", &option); switch (option) { case 1: insert(); break; case 2: delete(); break; case 3: display(); break; case 4: count(); break; default: break; } } return 0; } void insert() { printf("\nEnter Element for Insert Linked List : \n"); scanf("%d", &data); temp_node = (DATA_NODE *) malloc(sizeof (DATA_NODE)); temp_node->value = data; if (first_node == 0) { first_node = temp_node; } else { head_node->next = temp_node; } temp_node->next = 0; head_node = temp_node; fflush(stdin); } void delete() { int countvalue, pos, i = 0; countvalue = count(); temp_node = first_node; printf("\nDisplay Linked List : \n"); printf("\nEnter Position for Delete Element : \n"); scanf("%d", &pos); if (pos > 0 && pos <= countvalue) { if (pos == 1) { temp_node = temp_node -> next; first_node = temp_node; printf("\nDeleted Successfully \n\n"); } else { while (temp_node != 0) { if (i == (pos - 1)) { prev_node->next = temp_node->next; if(i == (countvalue - 1)) { head_node = prev_node; } printf("\nDeleted Successfully \n\n"); break; } else { i++; prev_node = temp_node; temp_node = temp_node -> next; } } } } else printf("\nInvalid Position \n\n"); } void display() { int count = 0; temp_node = first_node; printf("\nDisplay Linked List : \n"); while (temp_node != 0) { printf("# %d # ", temp_node->value); count++; temp_node = temp_node -> next; } printf("\nNo Of Items In Linked List : %d\n", count); } int count() { int count = 0; temp_node = first_node; while (temp_node != 0) { count++; temp_node = temp_node -> next; } printf("\nNo Of Items In Linked List : %d\n", count); return count; }

Singly Linked List Java Example

Posted by: Anmol Deep in Core Java May 26th, 2020 1 Comment

In this example, we shall discuss how to create a Singly Linked List in Java. We will also go through some live code demonstrating different operations on a Singly Linked List.

You can also check this tutorial in the following video:

Java LinkedList Tutorial – video

Types of Linked List and Operation on Linked List

Program to create, insert, delete and display operations on singly linked list in java

In the previous blog, we have seen the structure and properties of a Linked List. In this blog, we will discuss the types of a linked list and basic operations that can be performed on a linked list.

Types of Linked List

Following are the types of linked list

  1. Singly Linked List.
  2. Doubly Linked List.
  3. Circular Linked List.

Singly Linked List

A Singly-linked list is a collection of nodes linked together in a sequential way where each node of the singly linked list contains a data field and an address field that contains the reference of the next node.

The structure of the node in the Singly Linked List is

Program to create, insert, delete and display operations on singly linked list in java
class Node { int data // variable to store the data of the node Node next // variable to store the address of the next node }

The nodes are connected to each other in this form where the value of the next variable of the last node is NULL i.e. next = NULL, which indicates the end of the linked list.

Program to create, insert, delete and display operations on singly linked list in java

Doubly Linked List

A Doubly Linked List contains an extra memory to store the address of the previous node, together with the address of the next node and data which are there in the singly linked list. So, here we are storing the address of the next as well as the previous nodes.

The following is the structure of the node in the Doubly Linked List(DLL):

Program to create, insert, delete and display operations on singly linked list in java
class DLLNode { int val // variable to store the data of the node DLLNode prev // variable to store the address of the previous node DLLNode next // variable to store the address of the next node }

The nodes are connected to each other in this form where the first node has prev = NULL and the last node has next = NULL.

Program to create, insert, delete and display operations on singly linked list in java

Advantages over Singly Linked List-

  • It can be traversed both forward and backward direction.
  • The delete operation is more efficient if the node to be deleted is given. (Think! you will get the answer in the second half of this blog)
  • The insert operation is more efficient if the node is given before which insertion should take place. (Think!)

Disadvantages over Singly Linked List-

  • It will require more space as each node has an extra memory to store the address of the previous node.
  • The number of modification increase while doing various operations like insertion, deletion, etc.

Circular Linked List

A circular linked list is either a singly or doubly linked list in which there are no NULL values. Here, we can implement the Circular Linked List by making the use of Singly or Doubly Linked List. In the case of a singly linked list, the next of the last node contains the address of the first node and in case of a doubly-linked list, the next of last node contains the address of the first node and prev of the first node contains the address of the last node.

Program to create, insert, delete and display operations on singly linked list in java

Advantages of a Circular linked list

  • The list can be traversed from any node.
  • Circular lists are the required data structure when we want a list to be accessed in a circle or loop.
  • We can easily traverse to its previous node in a circular linked list, which is not possible in a singly linked list. (Think!)

Disadvantages of Circular linked list

  • If not traversed carefully, then we could end up in an infinite loop because here we don't have any NULL value to stop the traversal.
  • Operations in a circular linked list are complex as compared to a singly linked list and doubly linked list like reversing a circular linked list, etc.

Basic Operations on Linked List

  • Traversal: To traverse all the nodes one after another.
  • Insertion: To add a node at the given position.
  • Deletion: To delete a node.
  • Searching: To search an element(s) by value.
  • Updating: To update a node.
  • Sorting: To arrange nodes in a linked list in a specific order.
  • Merging: To merge two linked lists into one.

We will see the various implementation of these operations on a singly linked list.

Following is the structure of the node in a linked list:

class Node{ int data // variable containing the data of the node Node next // variable containing the address of next node }

Linked List Traversal

The idea here is to step through the list from beginning to end. For example, we may want to print the list or search for a specific node in the list.

The algorithm for traversing a list

  • Start with the head of the list. Access the content of the head node if it is not null.
  • Then go to the next node(if exists) and access the node information
  • Continue until no more nodes (that is, you have reached the null node)
void traverseLL(Node head) { while(head != NULL) { print(head.data) head = head.next } }

Linked List node Insertion

There can be three cases that will occur when we are inserting a node in a linked list.

  • Insertion at the beginning
  • Insertion at the end. (Append)
  • Insertion after a given node
Insertion at the beginning

Since there is no need to find the end of the list. If the list is empty, we make the new node as the head of the list. Otherwise, we we have to connect the new node to the current head of the list and make the new node, the head of the list.

Program to create, insert, delete and display operations on singly linked list in java
// function is returning the head of the singly linked-list Node insertAtBegin(Node head, int val) { newNode = new Node(val) // creating new node of linked list if(head == NULL) // check if linked list is empty return newNode else // inserting the node at the beginning { newNode.next = head return newNode } }
Insertion at end

We will traverse the list until we find the last node. Then we insert the new node to the end of the list. Note that we have to consider special cases such as list being empty.

In case of a list being empty, we will return the updated head of the linked list because in this case, the inserted node is the first as well as the last node of the linked list.

Program to create, insert, delete and display operations on singly linked list in java
// the function is returning the head of the singly linked list Node insertAtEnd(Node head, int val) { if( head == NULL ) // handing the special case { newNode = new Node(val) head = newNode return head } Node temp = head // traversing the list to get the last node while( temp.next != NULL ) { temp = temp.next } newNode = new Node(val) temp.next = newNode return head }
Insertion after a given node

We are given the reference to a node, and the new node is inserted after the given node.

Program to create, insert, delete and display operations on singly linked list in java
void insertAfter(Node prevNode, int val) { newNode = new Node(val) newNode.next = prevNode.next prevNode.next = newNode }

NOTE: If the address of the prevNode is not given, then you can traverse to that node by finding the data value.

Linked List node Deletion

To delete a node from a linked list, we need to do these steps

  • Find the previous node of the node to be deleted.
  • Change the next pointer of the previous node
  • Free the memory of the deleted node.

In the deletion, there is a special case in which the first node is deleted. In this, we need to update the head of the linked list.

Program to create, insert, delete and display operations on singly linked list in java
// this function will return the head of the linked list Node deleteLL(Node head, Node del) { if(head == del) // if the node to be deleted is the head node { return head.next // special case for the first Node } Node temp = head while( temp.next != NULL ) { if(temp.next == del) // finding the node to be deleted { temp.next = temp.next.next delete del // free the memory of that Node return head } temp = temp.next } return head // if no node matches in the Linked List }

Linked List node Searching

To search any value in the linked list, we can traverse the linked list and compares the value present in the node.

bool searchLL(Node head, int val) { Node temp = head // creating a temp variable pointing to the head of the linked list while( temp != NULL) // traversing the list { if( temp.data == val ) return true temp = temp.next } return false }

Linked List node Updation

To update the value of the node, we just need to set the data part to the new value.

Below is the implementation in which we had to update the value of the first node in which data is equal to val and we have to set it to newVal.

void updateLL(Node head, int val, int newVal) { Node temp = head while(temp != NULL) { if( temp.data == val) { temp.data = newVal return } temp = temp.next } }

Suggested Problems to solve in Linked List

  • Reverse linked list
  • Middle of the Linked List
  • Odd even linked List
  • Remove Duplicates from Sorted List
  • Merge Sort on Linked List
  • Check if a singly linked list is a palindrome
  • Detect and Remove Loop in a Linked List
  • Sort a linked list using insertion sort
  • Remove Nth Node from List End

Happy coding! Enjoy Algorithms.