# How To Insert At End of a Linked List at Constant Time – O(1)

In this tutorial i am going to show you how i insert at the end of a linked list in constant time – O(1) – time complexity as against the usual O(n).

They trick to insert at the end of a linked list each time at constant time – O(1) – is to avoid traversing the list to find the end of the list before insert by having a pointer point to the end of the linked list at all time – which i will call Tail in this post.

So the logic is very simple: create two global pointers called Head and Tail, then create a new node and assign value to the data part of the node and assign NULL to the link part. Now check if the Head pointer is NULL, if NULL, then list is empty; so make both pointer – Head and Tail – point to the newnode; now we have our first node in the linked list; otherwise if the head pointer is not NULL – meaning we have at least one node in our linked list, then point the Tail pointer link part to the newnode and then make the Tail pointer now point on the newnode – thereby indicating that the newnode is the last node in the list. With this Tail pointer always pointing to the last node, you can achieve inserting a new node at the end of a linked list at constant time O(1).

### Code Implementation in c

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

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

while(temp != NULL){
printf("%d ", temp->data);
temp = temp->next;
}
free(temp);
return 0;
}

struct node *Tail;

struct node *newnode = malloc(sizeof(struct node));
newnode->data = val;
newnode->next = NULL;
}else{
Tail->next = newnode;
Tail = newnode;
}
}

int main(){
}``````

## How To Calculate Time Complexity And Space Complexity Of An Algorithm – Big O Notation Examples

How to calculate time complexity and space complexity of an algorithm show developers who are new to the…

## Coin change problem all combinations in javascript

In this solution, we will be exploring the option of going through all combination to count the number…

## bfs and dfs program in c++ with output

In this tutorial, i will show you bfs and dfs program in c++ with output. The main difference…

## minimum coin change problem with recursion and memoization in javascript

The Problem is to find the minimum number of coins required for constructing a sum. This is a…

## Merge Sort Algorithm With Examples

In this tutorial, i will show you the Merge Sort Algorithm with some examples for quick understanding. I…

## Singly Linked List – Insert a New Node at the beginning of the list each time.

Singly Linked List – Insert each time at beginning of the list. In this tutorial, you will learn…