Introduction to Singly Linked ListSingly Linked List is a variant of Linked List which allows only forward traversal of linked lists. This is a simple form, yet it is effective for several problems such as Big Integer calculations. Show A singly linked list is made up of nodes where each node has two parts:
The beginning of the node marked by a special pointer named START. The pointer points to the fist node of the list but the link part of the last node has no next node to point to. The main difference from an array is:
In Singly Linked List, only the pointer to the first node is stored. The other nodes are accessed one by one. To get the address of ith node, we need to traverse all nodes before it because the address of ith node is stored with i-1th node and so on. Insert N elements in a Linked List one after other at middle positionGiven an array of N elements. The task is to insert the given elements at the middle position in the linked list one after another. Each insert operation should take O(1) time complexity.
Recommended: Please try your approach on {IDE} first, before moving on to the solution. Approach: There are two cases:
We take one additional pointer ‘middle’ which stores the address of current middle element and a counter which counts the total number of elements. C++
Java
Python3
C#
Javascript
Output:
1 -> 3 -> 5 -> 4 -> 2 -> NULL
Time Complexity : O(N)
Article Tags :
Data Structures Linked List Mathematical
Practice Tags :
Data Structures Linked List Mathematical Linked List | Set 2 (Inserting a node)We have introduced Linked Lists in the previous post. We also created a simple linked list with 3 nodes and discussed linked list traversal. C++
C
Java
Python
C#
Javascript
In this post, methods to insert a new node in linked list are discussed. A node can be added in three ways |