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
  • return True

Example

Let us see the following implementation to get better understanding −

 Live Demo

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

Updated on: 18-Jan-2021

74 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements