# 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 Python.

Now that you have got an understanding of the basic concepts behind linked list and their types, it’s time to dive into the common operations that can be performed.

Two important points to remember:

`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;
};
```

## How to Traverse a Linked List

Displaying the contents of a linked list is very simple. We keep moving the temp node to the next one and display its contents.

When temp is `NULL`, we know that we have reached the end of the linked list so we get out of the while loop.

```
struct node *temp = head;
printf("nnList 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 --->

## How to Add Elements to a Linked List

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

### Add to the beginning

- Allocate memory for new node
- Store data
- Change next of new node to point to head
- Change head to point to recently created node

```
struct node *newNode;
newNode = malloc(sizeof(struct node));
newNode->data = 4;
newNode->next = head;
head = newNode;
```

### Add to the End

- Allocate memory for new node
- Store data
- Traverse to 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;
struct node *temp = head;
while(temp->next != NULL){
temp = temp->next;
}
temp->next = newNode;
```

### Add to the Middle

- Allocate memory and store data for new node
- Traverse to node just before the required position of new node
- Change next pointers to include new node in between

```
struct node *newNode;
newNode = malloc(sizeof(struct node));
newNode->data = 4;
struct node *temp = head;
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 delete either from the beginning, end or from a particular position.

### Delete from beginning

- Point head to the second 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 deleted
- 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

```
/* Linked list operations in Python */
/* Create a node */
class Node:
def __init__(self, item):
self.item = item
self.next = None
class LinkedList:
def __init__(self):
self.head = None
/* Insert at the beginning */
def insertAtBeginning(self, data):
new_node = Node(data)
new_node.next = self.head
self.head = new_node
/* 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)
if self.head is None:
self.head = new_node
return
last = self.head
while (last.next):
last = last.next
last.next = new_node
/* Deleting a node */
def deleteNode(self, position):
if self.head == None:
return
temp_node = self.head
if position == 0:
self.head = temp_node.next
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):
temp_node = self.head
while (temp_node):
print(str(temp_node.item) + " ", end="")
temp_node = temp_node.next
if __name__ == '__main__':
llist = LinkedList()
llist.insertAtEnd(1)
llist.insertAtBeginning(2)
llist.insertAtBeginning(3)
llist.insertAtEnd(4)
llist.insertAfter(llist.head.next, 5)
print('Linked list:')
llist.printList()
print("nAfter deleting an element:")
llist.deleteNode(3)
llist.printList()
```

# Python Example for Beginners

## Two Machine Learning Fields

There are two sides to machine learning:

**Practical Machine Learning:**This is about querying databases, cleaning data, writing scripts to transform data and gluing algorithm and libraries together and writing custom code to squeeze reliable answers from data to satisfy difficult and ill defined questions. It’s the mess of reality.**Theoretical Machine Learning**: This is about math and abstraction and idealized scenarios and limits and beauty and informing what is possible. It is a whole lot neater and cleaner and removed from the mess of reality.

**Data Science Resources: Data Science Recipes and Applied Machine Learning Recipes**

**Introduction to Applied Machine Learning & Data Science for Beginners, Business Analysts, Students, Researchers and Freelancers with Python & R Codes @ Western Australian Center for Applied Machine Learning & Data Science (WACAMLDS) !!!**

Latest end-to-end Learn by Coding Recipes in Project-Based Learning:

**Applied Statistics with R for Beginners and Business Professionals**

**Data Science and Machine Learning Projects in Python: Tabular Data Analytics**

**Data Science and Machine Learning Projects in R: Tabular Data Analytics**

**Python Machine Learning & Data Science Recipes: Learn by Coding**

**R Machine Learning & Data Science Recipes: Learn by Coding**

**Comparing Different Machine Learning Algorithms in Python for Classification (FREE)**

Disclaimer: The information and code presented within this recipe/tutorial is only for educational and coaching purposes for beginners and developers. Anyone can practice and apply the recipe/tutorial presented here, but the reader is taking full responsibility for his/her actions. The author (content curator) of this recipe (code / program) has made every effort to ensure the accuracy of the information was correct at time of publication. The author (content curator) does not assume and hereby disclaims any liability to any party for any loss, damage, or disruption caused by errors or omissions, whether such errors or omissions result from accident, negligence, or any other cause.The information presented here could also be found in public knowledge domains.