- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- 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
- Related Articles
- Remove Zero Sum Consecutive Nodes from Linked List in C++
- Check if list contains consecutive numbers in Python
- Check if a linked list is Circular Linked List in C++
- Check if linked list is sorted (Iterative and Recursive) in Python
- Check if elements of Linked List are present in pair in Python
- Program to swap nodes in a linked list in Python
- Program to reverse inner nodes of a linked list in python
- Check if a Linked List is Pairwise Sorted in C++
- Program to delete n nodes after m nodes from a linked list in Python
- Delete N nodes after M nodes of a linked list in C++?
- Delete alternate nodes of a Linked List in C++
- Count nodes in Circular linked list in C++
- Delete N nodes after M nodes of a linked list in C++ program
- Sum of the alternate nodes of linked list in C++
- Program to remove all nodes of a linked list whose value is same as in Python

Advertisements