# Python3 program to remove intermediate
# points in a linked list that represents
# horizontal and vertical line segments
import math
# Node has 3 fields including x, y
# coordinates and a pointer to next node
class Node:
def __init__(self, x, y):
self.x = x
self.y = y
self.next = None
# Function to insert a node at the beginning
def push(head_ref, x, y):
new_node = Node(x, y)
new_node.x = x
new_node.y = y
new_node.next = head_ref
head_ref = new_node
return head_ref
# Utility function to print
# a singly linked list
def printList(head):
temp = head
while (temp != None):
print("(", temp.x, ",",
temp.y, ")", end = "->",)
temp = temp.next
print()
# This function deletes middle nodes in a
# sequence of horizontal and vertical line
# segments represented by linked list.
def delete_Middle_Nodes(head):
temp = head.next
prev = head
while (temp):
# checking equality of point x
if (temp.x == prev.x):
curr = prev
prev = temp
temp = temp.next
# removing vertical points of line
# segment from linked list
while (temp != None and temp.x == prev.x):
curr.next = temp
#free(prev)
prev = temp
temp = temp.next
# checking equality of point y
elif (temp.y == prev.y):
curr = prev
prev = temp
temp = temp.next
# removing horizontal points of line
# segment from linked list
while (temp != None and temp.y == prev.y):
curr.next = temp
#free(prev)
prev = temp
temp = temp.next
else:
prev = temp
temp = temp.next
# Driver Code
if __name__=='__main__':
head = None
head = push(head, 40, 5)
head = push(head, 20, 5)
head = push(head, 10, 5)
head = push(head, 10, 8)
head = push(head, 10, 10)
head = push(head, 3, 10)
head = push(head, 1, 10)
head = push(head, 0, 10)
print("Given Linked List: \n", end = "")
printList(head)
delete_Middle_Nodes(head)
print("Modified Linked List: \n", end = "")
printList(head)
# This code is contributed by AbhiThakur