
- Python Basic Tutorial
- Python - Home
- Python - Overview
- Python - Environment Setup
- Python - Basic Syntax
- Python - Comments
- Python - Variables
- Python - Data Types
- Python - Operators
- Python - Decision Making
- Python - Loops
- Python - Numbers
- Python - Strings
- Python - Lists
- Python - Tuples
- Python - Dictionary
- Python - Date & Time
- Python - Functions
- Python - Modules
- Python - Files I/O
- Python - Exceptions
Check if elements of Linked List are present in pair in Python
Suppose we have a singly linked list. We have to check whether each element in the given linked list is present in a pair, in other words all elements occur even no. of times.
So, if the input is like list = [2,5,5,2,3,3], then the output will be True.
To solve this, we will follow these steps −
- xor_res := 0, current_node := head of linked list
- while current_node is not null, do
- xor_res := xor_res XOR value of current_node
- current_node := next of current_node
- return False when xor_res is non-zero otherwise True
Example
Let us see the following implementation to get better understanding −
class ListNode: def __init__(self, data, next = None): self.val = data self.next = next def make_list(elements): head = ListNode(elements[0]) for element in elements[1:]: ptr = head while ptr.next: ptr = ptr.next ptr.next = ListNode(element) return head def solve(head): xor_res = 0 current_node = head while current_node != None: xor_res = xor_res ^ current_node.val current_node = current_node.next return False if xor_res else True head = make_list([2,5,5,2,3,3]) print(solve(head))
Input
[2,5,5,2,3,3]
Output
True
- Related Articles
- Check if a pair with given product exists in Linked list in C++
- Python - Check if all elements in a List are same
- Python - Check if all elements in a list are identical
- Python – Check if elements index are equal for list elements
- Python – Check if elements in a specific index are equal for list elements
- Check if a linked list is Circular Linked List in C++
- Python – Check if any list element is present in Tuple
- Check if linked list is sorted (Iterative and Recursive) in Python
- Check if list contains all unique elements in Python
- Check if absolute difference of consecutive nodes is 1 in Linked List in Python
- Check if array elements are consecutive in Python
- Check if two list of tuples are identical in Python
- Check if substring present in string in Python
- Program to find out if a linked list is present in a given binary tree in Python
- Check if Queue Elements are pairwise consecutive in Python

Advertisements