
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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
Advertisements