Last active
May 31, 2017 06:10
-
-
Save anil477/47d59d8e3fbd4c7315627eda96dd3f78 to your computer and use it in GitHub Desktop.
Given a linked list of line segments, remove middle points
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Given a linked list of co-ordinates where adjacent points either form a vertical line or a horizontal line. | |
// Delete points from the linked list which are in the middle of a horizontal or vertical line. | |
// http://www.geeksforgeeks.org/given-linked-list-line-segments-remove-middle-points/ | |
// The idea is to keep track of current node, next node and next-next node. | |
// While the next node is same as next-next node, keep deleting the next node. | |
// In this complete procedure we need to keep an eye on shifting of pointers and checking for NULL values. | |
class Node { | |
int x; | |
int y; | |
Node next; | |
Node(int a, int b) | |
{ | |
x = a; | |
y = b; | |
next = null; | |
} | |
} | |
class LinkedList | |
{ | |
Node head; // head of list | |
/* This function prints contents of linked list starting from head */ | |
public void printList() | |
{ | |
Node temp = head; | |
System.out.println( " Print Function "); | |
while (temp != null) | |
{ | |
System.out.println( " Data: " + temp.x + " " + temp.y); | |
temp = temp.next; | |
} | |
} | |
public static void main(String[] args) | |
{ | |
LinkedList llist = new LinkedList(); | |
llist.head = new Node(0,10); | |
llist.addAtEnd(1,10); | |
llist.addAtEnd(5,10); | |
llist.addAtEnd(7,10); | |
llist.addAtEnd(7,5); | |
llist.addAtEnd(20,5); | |
llist.addAtEnd(40,5); | |
llist.printList(); | |
llist.remove(); | |
llist.printList(); | |
} | |
public void remove() | |
{ | |
Node current = this.head; | |
Node next = null; | |
Node next_next = null; | |
while(current !=null && current.next !=null && current.next.next !=null) | |
{ | |
next = current.next; | |
next_next = current.next.next; | |
if((current.x == next.x && current.x == next_next.x) || | |
(current.y == next.y && current.y == next_next.y)) | |
{ | |
current.next = current.next.next; | |
} | |
else | |
{ | |
current = current.next; | |
} | |
} | |
} | |
public void addAtHead(int x, int y) | |
{ | |
Node node = new Node(x, y); | |
node.next = this.head; | |
this.head = node; | |
} | |
public void addAtEnd(int x, int y) | |
{ | |
Node node = new Node(x, y); | |
Node temp = this.head; | |
// find the tail node | |
while(temp.next != null) | |
{ | |
temp = temp.next; | |
} | |
temp.next = node; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment