# Linked List Operations: Traverse, Insert and Delete

In this tutorial, you will learn various operations on a linked list. Additionally, you will discover the implementation of linked list operations in C/C++, Python, and Java

Contents

A linked list is a very commonly used linear data structure that comprises a group of nodes in a sequence.

Each node holds its own data and the address of the next node thus forming a chain-like structure.

Linked Lists are used to create trees and graphs.

Since you have a comprehension of the fundamental ideas behind the linked list and their types, it’s time to dive into the common operations that can be performed.

Two significant points to recall:

• next pointer of the last node is NULL, so if the next current node is NULL, we have arrived at the finish of the linked list.

In the entirety of the examples, we will assume that the linked list has three nodes 1 – >2 – >3 with node structure as beneath:

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

## How to Traverse a Linked List

Showing the substance of a linked list is basic. We continue to move the temp node to the next one and show its substance.

At the point when temp is NULL, we realize that we have arrived at the finish of the linked list so we get out the while loop.

```struct node *temp = head;
printf("\n\nList elements are - \n");
while(temp != NULL)
{
printf("%d --->",temp->data);
temp = temp->next;
}```

The output of this program will be:

```List elements are -
1 --->2 --->3 --->```

You can add elements to either the beginning, middle, or end of the linked list.

• Allocate memory for the new node
• Store data
• Change next of new node to point to head
• Change head to point to the recently created node
```struct node *newNode;
newNode = malloc(sizeof(struct node));
newNode->data = 4;

• Allocate memory for the new node
• Store data
• Traverse to the last node
• Change next of last node to recently created node
```struct node *newNode;
newNode = malloc(sizeof(struct node));
newNode->data = 4;
newNode->next = NULL;

while(temp->next != NULL){
temp = temp->next;
}

temp->next = newNode;```

• Allocate memory and store data for the new node
• Traverse to node just before the required position of the new node
• Change next pointers to include new node in between
```struct node *newNode;
newNode = malloc(sizeof(struct node));
newNode->data = 4;

for(int i=2; i < position; i++) {
if(temp->next != NULL) {
temp = temp->next;
}
}
newNode->next = temp->next;
temp->next = newNode;```

## How to Delete from a Linked List

You can erase either from the beginning, end, or from a specific position.

### Delete from starting

• Points head toward the subsequent node
`head = head->next;`

### Delete from end

• Traverse to second last element
• Change its next pointer to null
```struct node* temp = head;
while(temp->next->next!=NULL){
temp = temp->next;
}
temp->next = NULL;```

### Delete from middle

Traverse to element before the element to be erased

Change next pointers to exclude the node from the chain

```for(int i=2; i< position; i++) {
if(temp->next!=NULL) {
temp = temp->next;
}
}

temp->next = temp->next->next;
```

## Implementing LinkedList Operations in Python, Java, C, and C++

Python

```# Linked list operations in Python

# Create a node
class Node:
def __init__(self, item):
self.item = item
self.next = None

def __init__(self):

# Insert at the beginning
def insertAtBeginning(self, data):
new_node = Node(data)

# Insert after a node
def insertAfter(self, node, data):

if node is None:
print("The given previous node must inLinkedList.")
return

new_node = Node(data)
new_node.next = node.next
node.next = new_node

# Insert at the end
def insertAtEnd(self, data):
new_node = Node(data)

return

while (last.next):
last = last.next

last.next = new_node

# Deleting a node
def deleteNode(self, position):

return

if position == 0:
temp_node = None
return

# Find the key to be deleted
for i in range(position - 1):
temp_node = temp_node.next
if temp_node is None:
break

# If the key is not present
if temp_node is None:
return

if temp_node.next is None:
return

next = temp_node.next.next
temp_node.next = None
temp_node.next = next

def printList(self):
while (temp_node):
print(str(temp_node.item) + " ", end="")
temp_node = temp_node.next

if __name__ == '__main__':

llist.insertAtEnd(1)
llist.insertAtBeginning(2)
llist.insertAtBeginning(3)
llist.insertAtEnd(4)

llist.printList()

print("\nAfter deleting an element:")
llist.deleteNode(3)
llist.printList()```

Java

```// Linked list operations in Java

// Create a node
class Node {
int item;
Node next;

Node(int d) {
item = d;
next = null;
}
}

public void insertAtBeginning(int data) {
// insert the item
Node new_node = new Node(data);
}

public void insertAfter(Node prev_node, int data) {
if (prev_node == null) {
System.out.println("The given previous node cannot be null");
return;
}
Node new_node = new Node(data);
new_node.next = prev_node.next;
prev_node.next = new_node;
}

public void insertAtEnd(int data) {
Node new_node = new Node(data);

return;
}

new_node.next = null;

while (last.next != null)
last = last.next;

last.next = new_node;
return;
}

void deleteNode(int position) {
return;

if (position == 0) {
return;
}
// Find the key to be deleted
for (int i = 0; node != null && i < position - 1; i++)
node = node.next;

// If the key is not present
if (node == null || node.next == null)
return;

// Remove the node
Node next = node.next.next;

node.next = next;
}

public void printList() {
while (node != null) {
System.out.print(node.item + " ");
node = node.next;
}
}

public static void main(String[] args) {

llist.insertAtEnd(1);
llist.insertAtBeginning(2);
llist.insertAtBeginning(3);
llist.insertAtEnd(4);

llist.printList();

System.out.println("\nAfter deleting an element: ");
llist.deleteNode(3);
llist.printList();
}
}```

C

```// Linked list operations in C

#include <stdio.h>
#include <stdlib.h>

// Create a node
struct Node {
int item;
struct Node* next;
};

void insertAtBeginning(struct Node** ref, int data) {
// Allocate memory to a node
struct Node* new_node = (struct Node*)malloc(sizeof(struct Node));

// insert the item
new_node->item = data;
new_node->next = (*ref);

// Move head to new node
(*ref) = new_node;
}

// Insert a node after a node
void insertAfter(struct Node* node, int data) {
if (node == NULL) {
printf("the given previous node cannot be NULL");
return;
}

struct Node* new_node = (struct Node*)malloc(sizeof(struct Node));
new_node->item = data;
new_node->next = node->next;
node->next = new_node;
}

void insertAtEnd(struct Node** ref, int data) {
struct Node* new_node = (struct Node*)malloc(sizeof(struct Node));
struct Node* last = *ref;

new_node->item = data;
new_node->next = NULL;

if (*ref == NULL) {
*ref = new_node;
return;
}

while (last->next != NULL)
last = last->next;

last->next = new_node;
return;
}

void deleteNode(struct Node** ref, int key) {
struct Node *temp = *ref, *prev;

if (temp != NULL && temp->item == key) {
*ref = temp->next;
free(temp);
return;
}
// Find the key to be deleted
while (temp != NULL && temp->item != key) {
prev = temp;
temp = temp->next;
}

// If the key is not present
if (temp == NULL) return;

// Remove the node
prev->next = temp->next;

free(temp);
}

void printList(struct Node* node) {
while (node != NULL) {
printf(" %d ", node->item);
node = node->next;
}
}

// Driver program
int main() {

printf("\nAfter deleting an element: ");
}
```

C++

```// Linked list operations in C++

#include <stdlib.h>
#include <iostream>

using namespace std;

// Create a node
struct Node {
int item;
struct Node* next;
};

void insertAtBeginning(struct Node** ref, int data) {

// Allocate memory to a node
struct Node* new_node = (struct Node*)malloc(sizeof(struct Node));

// insert the item
new_node->item = data;
new_node->next = (*ref);

// Move head to new node
(*ref) = new_node;
}

// Insert a node after a node
void insertAfter(struct Node* prev_node, int data) {
if (prev_node == NULL) {
cout << "the given previous node cannot be NULL";
return;
}

struct Node* new_node = (struct Node*)malloc(sizeof(struct Node));
new_node->item = data;
new_node->next = prev_node->next;
prev_node->next = new_node;
}

void insertAtEnd(struct Node** ref, int data) {
struct Node* new_node = (struct Node*)malloc(sizeof(struct Node));
struct Node* last = *ref;

new_node->item = data;
new_node->next = NULL;

if (*ref == NULL) {
*ref = new_node;
return;
}

while (last->next != NULL)
last = last->next;

last->next = new_node;
return;
}

void deleteNode(struct Node** ref, int key) {
struct Node *temp = *ref, *prev;

if (temp != NULL && temp->item == key) {
*ref = temp->next;
free(temp);
return;
}
// Find the key to be deleted
while (temp != NULL && temp->item != key) {
prev = temp;
temp = temp->next;
}

// If the key is not present
if (temp == NULL) return;

// Remove the node
prev->next = temp->next;

free(temp);
}

void printList(struct Node* node) {
while (node != NULL) {
cout << node->item << " ";
node = node->next;
}
}

// Driver program
int main() {