First non-repeating in a linked list
Last Updated :
24 Jul, 2023
Given a linked list, find its first non-repeating integer element.
Examples:
Input : 10->20->30->10->20->40->30->NULL
Output :First Non-repeating element is 40.
Input :1->1->2->2->3->4->3->4->5->NULL
Output :First Non-repeating element is 5.
Input :1->1->2->2->3->4->3->4->NULL
Output :No NOn-repeating element is found.
- Create a hash table and marked all elements as zero.
- Traverse the linked list and count the frequency of all the elements in the hashtable.
- Traverse the linked list again and see the element whose frequency is 1 in the hashtable.
Implementation:
C++
// C++ program to find first non-repeating
// element in a linked list
#include<bits/stdc++.h>
using namespace std;
/* Link list node */
struct Node
{
int data;
struct Node* next;
};
/* Function to find the first non-repeating
element in the linked list */
int firstNonRepeating(struct Node *head)
{
// Create an empty map and insert all linked
// list elements into hash table
unordered_map<int, int> mp;
for (Node *temp=head; temp!=NULL; temp=temp->next)
mp[temp->data]++;
// Traverse the linked list again and return
// the first node whose count is 1
for (Node *temp=head; temp!=NULL; temp=temp->next)
if (mp[temp->data] == 1)
return temp->data;
return -1;
}
/* Function to push a node */
void push(struct Node** head_ref, int new_data)
{
struct Node* new_node =
(struct Node*) malloc(sizeof(struct Node));
new_node->data = new_data;
new_node->next = (*head_ref);
(*head_ref) = new_node;
}
/* Driver program to test above function*/
int main()
{
// Let us create below linked list.
// 85->15->18->20->85->35->4->20->NULL
struct Node* head = NULL;
push(&head, 20);
push(&head, 4);
push(&head, 35);
push(&head, 85);
push(&head, 20);
push(&head, 18);
push(&head, 15);
push(&head, 85);
cout << firstNonRepeating(head);
return 0;
}
Java
/*package whatever //do not write package name here */
import java.io.*;
import java.util.*;
class GFG
{
// Java program to find first non-repeating
// element in a linked list
/* Link list node */
static class Node
{
public int data;
public Node next;
public Node(){
this.data = 0;
this.next = null;
}
public Node(int data,Node next){
this.data = data;
this.next = next;
}
};
/* Function to find the first non-repeating
element in the linked list */
static int firstNonRepeating(Node head)
{
// Create an empty map and insert all linked
// list elements into hash table
HashMap<Integer,Integer> mp = new HashMap<>();
for (Node temp=head; temp != null; temp = temp.next){
if(mp.containsKey(temp.data)){
mp.put(temp.data,mp.get(temp.data)+1);
}
else{
mp.put(temp.data,1);
}
}
// Traverse the linked list again and return
// the first node whose count is 1
for (Node temp=head; temp!=null; temp=temp.next){
if (mp.get(temp.data) == 1)
return temp.data;
}
return -1;
}
/* Function to push a node */
static Node push(Node head_ref, int new_data)
{
Node new_node = new Node();
new_node.data = new_data;
new_node.next = head_ref;
head_ref = new_node;
return head_ref;
}
/* Driver program to test above function*/
public static void main(String args[])
{
// Let us create below linked list.
// 85->15->18->20->85->35->4->20->NULL
Node head = null;
head = push(head, 20);
head = push(head, 4);
head = push(head, 35);
head = push(head, 85);
head = push(head, 20);
head = push(head, 18);
head = push(head, 15);
head = push(head, 85);
System.out.print(firstNonRepeating(head));
}
}
// This code is contributed by shinjanpatra
Python3
# Python3 program to find first non-repeating
# element in a linked list
# Link list node
class Node:
def __init__(self, data):
self.data = data
self.next = None
# Function to find the first non-repeating
# element in the linked list
def firstNonRepeating(head):
# Create an empty map and insert all linked
# list elements into hash table
mp = dict()
temp = head
while (temp != None):
if temp.data not in mp:
mp[temp.data] = 0
mp[temp.data] += 1
temp = temp.next
temp = head
# Traverse the linked list again and return
# the first node whose count is 1
while (temp != None):
if temp.data in mp:
if mp[temp.data] == 1:
return temp.data
temp = temp.next
return -1
# Function to push a node
def push(head_ref, new_data):
new_node = Node(new_data)
new_node.next = head_ref
head_ref = new_node
return head_ref
# Driver code
if __name__=='__main__':
# Let us create below linked list.
# 85->15->18->20->85->35->4->20->NULL
head = None
head = push(head, 20)
head = push(head, 4)
head = push(head, 35)
head = push(head, 85)
head = push(head, 20)
head = push(head, 18)
head = push(head, 15)
head = push(head, 85)
print(firstNonRepeating(head))
# This code is contributed by rutvik_56
C#
using System;
using System.Collections.Generic;
public class Gfg {
static void Main(string[] args)
{
// Let us create below linked list.
// 85->15->18->20->85->35->4->20->NULL
Node head = null;
push(ref head, 20);
push(ref head, 4);
push(ref head, 35);
push(ref head, 85);
push(ref head, 20);
push(ref head, 18);
push(ref head, 15);
push(ref head, 85);
Console.WriteLine(firstNonRepeating(head));
}
// Function to find the first non-repeating
// element in the linked list
static int firstNonRepeating(Node head)
{
// Create an empty map and insert all linked
// list elements into hash table
Dictionary<int, int> mp
= new Dictionary<int, int>();
for (Node temp = head; temp != null;
temp = temp.next)
if (mp.ContainsKey(temp.data))
mp[temp.data]++;
else
mp[temp.data] = 1;
// Traverse the linked list again and return
// the first node whose count is 1
for (Node temp = head; temp != null;
temp = temp.next)
if (mp[temp.data] == 1)
return temp.data;
return -1;
}
// Function to push a node
static void push(ref Node headRef, int newData)
{
Node newNode
= new Node{ data = newData, next = headRef };
headRef = newNode;
}
class Node {
public int data;
public Node next;
}
}
JavaScript
<script>
// Javascript program to find first non-repeating
// element in a linked list
/* Link list node */
class Node
{
constructor()
{
this.data = 0;
this.next = null;
}
};
/* Function to find the first non-repeating
element in the linked list */
function firstNonRepeating(head)
{
// Create an empty map and insert all linked
// list elements into hash table
var mp = new Map();
for (var temp=head; temp!=null; temp=temp.next)
{
if(mp.has(temp.data))
{
mp.set(temp.data , mp.get(temp.data)+1)
}
else
{
mp.set(temp.data, 1)
}
}
// Traverse the linked list again and return
// the first node whose count is 1
for (var temp=head; temp!=null; temp=temp.next)
if (mp.get(temp.data) == 1)
return temp.data;
return -1;
}
/* Function to push a node */
function push(head_ref, new_data)
{
var new_node = new Node();
new_node.data = new_data;
new_node.next = (head_ref);
(head_ref) = new_node;
return head_ref;
}
/* Driver program to test above function*/
// Let us create below linked list.
// 85.15.18.20.85.35.4.20.null
var head = null;
head = push(head, 20);
head = push(head, 4);
head = push(head, 35);
head = push(head, 85);
head = push(head, 20);
head = push(head, 18);
head = push(head, 15);
head = push(head, 85);
document.write( firstNonRepeating(head));
</script>
Time Complexity: O(N)
Auxiliary Space: O(N), for the map
Approach : Using two loops
In this approach, we use two loops to traverse the linked list. For each node in the linked list, we traverse the rest of the linked list to check if it is a non-repeating node. If we find a node that is not repeated in the linked list, we return that node.
Traverse the linked list starting from the head node.
For each node in the linked list, traverse the rest of the linked list to check if it is a non-repeating node.
To check if a node is non-repeating, compare its data value with the data value of all the nodes after it in the linked list. If there is another node with the same data value, then the current node is not a non-repeating node.
If a non-repeating node is found, return its data value.
If no non-repeating node is found, return -1 to indicate that no non-repeating node exists in the linked list.
Time Complexity:
C++
// C++ program to find first non-repeating
// element in a linked list
#include<bits/stdc++.h>
using namespace std;
/* Link list node */
struct Node
{
int data;
struct Node* next;
};
/* Function to find the first non-repeating
element in the linked list */
// Function to find the first non-repeating element in a linked list
int firstNonRepeatingNode(Node* head) {
Node* curr = head;
while (curr != NULL) {
bool isNonRepeating = true;
Node* temp = head;
while (temp != NULL) {
if (curr != temp && curr->data == temp->data) {
isNonRepeating = false;
break;
}
temp = temp->next;
}
if (isNonRepeating) {
return curr->data;
}
curr = curr->next;
}
return -1; // No non-repeating node found
}
/* Function to push a node */
void push(struct Node** head_ref, int new_data)
{
struct Node* new_node =
(struct Node*) malloc(sizeof(struct Node));
new_node->data = new_data;
new_node->next = (*head_ref);
(*head_ref) = new_node;
}
/* Driver program to test above function*/
int main()
{
// Let us create below linked list.
// 85->15->18->20->85->35->4->20->NULL
struct Node* head = NULL;
push(&head, 20);
push(&head, 4);
push(&head, 35);
push(&head, 85);
push(&head, 20);
push(&head, 18);
push(&head, 15);
push(&head, 85);
cout << firstNonRepeatingNode(head);
return 0;
}
Java
// Java program to find the first non-repeating element in a linked list
import java.util.*;
// Link list node
class Node {
int data;
Node next;
// Constructor
public Node(int data) {
this.data = data;
this.next = null;
}
}
// Class to represent a linked list
class LinkedList {
// Function to find the first non-repeating element in a linked list
static int firstNonRepeatingNode(Node head) {
Node curr = head;
while (curr != null) {
boolean isNonRepeating = true;
Node temp = head;
while (temp != null) {
if (curr != temp && curr.data == temp.data) {
isNonRepeating = false;
break;
}
temp = temp.next;
}
if (isNonRepeating) {
return curr.data;
}
curr = curr.next;
}
return -1; // No non-repeating node found
}
// Function to push a node at the beginning of the linked list
static Node push(Node head_ref, int new_data) {
Node new_node = new Node(new_data);
new_node.next = head_ref;
head_ref = new_node;
return head_ref;
}
// Driver program to test above functions
public static void main(String[] args) {
// Let us create a linked list: 85->15->18->20->85->35->4->20->NULL
Node head = null;
head = push(head, 20);
head = push(head, 4);
head = push(head, 35);
head = push(head, 85);
head = push(head, 20);
head = push(head, 18);
head = push(head, 15);
head = push(head, 85);
// Find the first non-repeating element in the linked list
int result = firstNonRepeatingNode(head);
System.out.println(result);
}
}
// THIS CODE IS CONTRIBUTED BY CHANDAN AGARWAL
Python3
# Python program to find first non-repeating
# element in a linked list
# Link list node
class Node:
def __init__(self, data):
self.data = data
self.next = None
# Function to find the first non-repeating element in a linked list
def firstNonRepeatingNode(head):
curr = head
while curr != None:
isNonRepeating = True
temp = head
while temp != None:
if curr != temp and curr.data == temp.data:
isNonRepeating = False
break
temp = temp.next
if isNonRepeating:
return curr.data
curr = curr.next
return -1 # No non-repeating node found
# Function to push a node
def push(head_ref, new_data):
new_node = Node(new_data)
new_node.next = head_ref
head_ref = new_node
return head_ref
# Driver program to test above function
if __name__ == '__main__':
# Let us create below linked list.
# 85->15->18->20->85->35->4->20->NULL
head = None
head = push(head, 20)
head = push(head, 4)
head = push(head, 35)
head = push(head, 85)
head = push(head, 20)
head = push(head, 18)
head = push(head, 15)
head = push(head, 85)
print(firstNonRepeatingNode(head))
JavaScript
// Define the 'Node' class
class Node {
constructor(data) {
this.data = data;
this.next = null;
}
}
// Function to find the first non-repeating element in a linked list
function firstNonRepeatingNode(head) {
let curr = head;
while (curr !== null) {
let isNonRepeating = true;
let temp = head;
while (temp !== null) {
if (curr !== temp && curr.data === temp.data) {
isNonRepeating = false;
break;
}
temp = temp.next;
}
if (isNonRepeating) {
return curr.data;
}
curr = curr.next;
}
return -1; // No non-repeating node found
}
// Function to push a node
function push(head_ref, new_data) {
let new_node = new Node(new_data);
new_node.next = head_ref;
head_ref = new_node;
return head_ref;
}
// Driver program to test above functions
let head = null;
// Create the linked list
head = push(head, 20);
head = push(head, 4);
head = push(head, 35);
head = push(head, 85);
head = push(head, 20);
head = push(head, 18);
head = push(head, 15);
head = push(head, 85);
console.log(firstNonRepeatingNode(head));
// THIS CODE IS CONTRIBUTED BY CHANDAN AGARWAL
Output:
15
Time Complexity:
The time complexity of this approach is O(n^2), where n is the number of nodes in the linked list. This is because for each node in the linked list, we need to traverse the rest of the linked list to check if it is a non-repeating node. Therefore, the total number of comparisons required is n(n-1)/2, which is O(n^2).
Space Complexity:
The space complexity of this approach is O(1), as we are not using any extra data structures to store the nodes of the linked list or their frequency counts. We are only using a constant amount of memory to store the pointers and variables required to traverse the linked list and check for non-repeating nodes.
Further Optimisations:
The above solution requires two traversals of linked list. In case we have many repeating elements, we can save one traversal by storing positions also in hash table. Please refer last method of Given a string, find its first non-repeating character for details.
Similar Reads
Linked List meaning in DSA
A linked list is a linear data structure used for storing a sequence of elements, where each element is stored in a node that contains both the element and a pointer to the next node in the sequence. Linked ListTypes of linked lists: Linked lists can be classified in the following categories Singly
4 min read
Find first node of loop in a linked list
Given the head of a linked list that may contain a loop. A loop means that the last node of the linked list is connected back to a node in the same list. The task is to find the Starting node of the loop in the linked list if there is no loop in the linked list return -1.Example: Input: Output: 3Exp
14 min read
Rearrange a given linked list in-place
Given a singly linked list L0 -> L1 -> ⦠-> Ln-1 -> Ln. Rearrange the nodes in the list so that the newly formed list is : L0 -> Ln -> L1 -> Ln-1 -> L2 -> Ln-2 ... You are required to do this in place without altering the nodes' values. Examples: Input: 1 -> 2 -> 3 -
10 min read
Searching in Circular Linked list
Given a Circular Linked List CList, and an element K, the task is to check if this element K is present in the Circular Linked list or not. Example: Input: CList = 6->5->4->3->2, K = 3 Output: Found Input: CList = 6->5->4->3->2, K = 1 Output: Not Found Approach: The approach
7 min read
Detect and Remove Loop in Linked List
Given the head of a linked list that may contain a loop. A loop means that the last node of the linked list is connected back to a node in the same list. The task is to remove the loop from the linked list (if it exists).Example:Input: Output: 1 -> 3 -> 4 Explanation: The Loop is removed from
15 min read
Count Occurrences in a Linked List
Given a singly linked list and a key, the task is to count the number of occurrences of the given key in the linked list. Example : Input : head: 1->2->1->2->1->3->1 , key = 1Output : 4 Explanation: key equals 1 has 4 occurrences.Input : head: 1->2->1->2->1, key = 3Outp
9 min read
LinkedList addFirst() Method in Java
In Java, the addFirst() method of LinkedList, adds elements at the beginning of the list. All the existing elements moved one position to the right and the new element is placed at the beginning.Syntax of LinkedList addFirst() Method public void addFirst( E e)Parameters: E is the data type of elemen
1 min read
Replace nodes with duplicates in linked list
Given a linked list that contains some random integers from 1 to n with many duplicates. Replace each duplicate element that is present in the linked list with the values n+1, n+2, n+3 and so on(starting from left to right in the given linked list). Examples: Input : 1 3 1 4 4 2 1 Output : 1 3 5 4 6
9 min read
Find extra node in the second Linked list
Given two Linked list L1 and L2. The second list L2 contains all the nodes of L1 along with 1 extra node. The task is to find that extra node. Examples: Input: L1 = 17 -> 7 -> 6 -> 16 L2 = 17 -> 7 -> 6 -> 16 -> 15 Output: 15 Explanation: Element 15 is not present in the L1 listI
7 min read
Make a loop at k-th position in a linked list
Given a linked list and a position k. Make a loop at k-th position Examples: Input : Given linked list Output : Modified linked list Algorithm: Traverse the first linked list till k-th point Make backup of the k-th node Traverse the linked list till end Attach the last node with k-th node Implementa
8 min read