Open In App

First non-repeating in a linked list

Improve
Improve
Like Article
Like
Save
Share
Report

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.
  1. Create a hash table and marked all elements as zero. 
  2. Traverse the linked list and count the frequency of all the elements in the hashtable. 
  3. 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>


Output

15





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.  



Last Updated : 24 Jul, 2023
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads