
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 Absolute Difference of Consecutive Nodes 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