 
  Data Structure Data Structure
 Networking Networking
 RDBMS RDBMS
 Operating System Operating System
 Java Java
 MS Excel MS Excel
 iOS iOS
 HTML HTML
 CSS CSS
 Android Android
 Python Python
 C Programming C Programming
 C++ C++
 C# C#
 MongoDB MongoDB
 MySQL MySQL
 Javascript Javascript
 PHP 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 absolute difference of consecutive nodes is 1 in Linked List in Python
Suppose, we have a singly linked list where each node contains an integer value. We have to find out if the absolute difference between two successive nodes is 1.
So, if the input is like start_node->5->6->7->8->7->6->5->4, then the output will be True.
To solve this, we will follow these steps −
- temp := start_node
- while temp is not null, do- if temp.link is same as null, then- come out from the loop
 
- if |value of (temp) - value of (temp.link)| is not same as 1, then- return False
 
- temp := temp.link
 
- if temp.link is same as null, then
- return True
Example
Let us see the following implementation to get better understanding −
import math class link_node: def __init__(self, value): self.value = value self.link = None def create_node(value): temp = link_node(value) temp.value = value temp.link = None return temp def make_list(elements): head = link_node(elements[0]) for element in elements[1:]: ptr = head while ptr.link: ptr = ptr.link ptr.next = link_node(element) return head def solve(start_node): temp = start_node while (temp): if (temp.link == None): break if (abs((temp.value) - (temp.link.value)) != 1) : return False temp = temp.link return True start_node = make_list([5, 6, 7, 8, 7, 6, 5, 4]) print(solve(start_node))
Input
[5, 6, 7, 8, 7, 6, 5, 4]
Output
True
Advertisements
 