Given a linked list of line segments, remove middle points

Given a linked list of coordinates 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.
Examples:Â
Input: (0,10)->(1,10)->(5,10)->(7,10)
|
(7,5)->(20,5)->(40,5)
Output: Linked List should be changed to following
(0,10)->(7,10)
|
(7,5)->(40,5)
The given linked list represents a horizontal line from (0,10)
to (7, 10) followed by a vertical line from (7, 10) to (7, 5),
followed by a horizontal line from (7, 5) to (40, 5).
Input: (2,3)->(4,3)->(6,3)->(10,3)->(12,3)
Output: Linked List should be changed to following
(2,3)->(12,3)
There is only one vertical line, so all middle points are removed.
Source: Microsoft Interview Experience
The idea is to keep track of the current node, next node, and next-next node. While the next node is the same as the next-next node, keep deleting the next node. In this complete procedure, we need to keep an eye on the shifting of pointers and checking for NULL values.
Following are implementations of the above idea.Â
C++
// C++ program to remove intermediate points// in a linked list that represents horizontal// and vertical line segments #include <bits/stdc++.h>using namespace std; Â
// Node has 3 fields including x, y // coordinates and a pointer // to next node class Node { Â Â Â Â public:Â Â Â Â int x, y; Â Â Â Â Node *next; }; Â
/* Function to insert a node at the beginning */void push(Node ** head_ref, int x,int y) { Â Â Â Â Node* new_node =new Node();Â Â Â Â new_node->x = x; Â Â Â Â new_node->y = y; Â Â Â Â new_node->next = (*head_ref); Â Â Â Â (*head_ref) = new_node; } Â
/* Utility function to print a singly linked list */void printList(Node *head) { Â Â Â Â Node *temp = head; Â Â Â Â while (temp != NULL) Â Â Â Â { Â Â Â Â Â Â Â Â cout << "(" << temp->x << "," << temp->y << ")-> "; Â Â Â Â Â Â Â Â temp = temp->next; Â Â Â Â } Â Â Â Â cout<<endl;Â
} Â
// Utility function to remove Next from linked list // and link nodes after it to head void deleteNode(Node *head, Node *Next) { Â Â Â Â head->next = Next->next; Â Â Â Â Next->next = NULL; Â Â Â Â free(Next); } Â
// This function deletes middle nodes in a sequence of // horizontal and vertical line segments represented by // linked list. Node* deleteMiddle(Node *head) {     // If only one node or no node...Return back     if (head == NULL || head->next == NULL ||                     head->next->next == NULL)         return head; Â
    Node* Next = head->next;     Node *NextNext = Next->next ; Â
    // Check if this is a vertical line or horizontal line     if (head->x == Next->x)     {         // Find middle nodes with same x value, and delete them         while (NextNext != NULL && Next->x == NextNext->x)         {             deleteNode(head, Next); Â
            // Update Next and NextNext for next iteration             Next = NextNext;             NextNext = NextNext->next;         }     }     else if (head->y==Next->y) // If horizontal line     {         // Find middle nodes with same y value, and delete them         while (NextNext != NULL && Next->y == NextNext->y)         {             deleteNode(head, Next); Â
            // Update Next and NextNext for next iteration             Next = NextNext;             NextNext = NextNext->next;         }     }     else // Adjacent points must have either same x or same y     {         puts("Given linked list is not valid");         return NULL;     } Â
    // Recur for next segment     deleteMiddle(head->next); Â
    return head; } Â
// Driver program to test above functions int main() { Â Â Â Â Node *head = NULL; Â
    push(&head, 40,5);     push(&head, 20,5);     push(&head, 10,5);     push(&head, 10,8);     push(&head, 10,10);     push(&head, 3,10);     push(&head, 1,10);     push(&head, 0,10);     cout << "Given Linked List: \n";     printList(head); Â
    if (deleteMiddle(head) != NULL);     {         cout << "Modified Linked List: \n";         printList(head);     }     return 0; } // This is code is contributed by rathbhupendra |
C
// C program to remove intermediate points in a linked list // that represents horizontal and vertical line segments#include <stdio.h>#include <stdlib.h>Â
// Node has 3 fields including x, y coordinates and a pointer// to next nodestruct Node{Â Â Â Â int x, y;Â Â Â Â struct Node *next;};Â
/* Function to insert a node at the beginning */void push(struct Node ** head_ref, int x,int y){    struct Node* new_node =            (struct Node*) malloc(sizeof(struct Node));    new_node->x = x;    new_node->y = y;    new_node->next = (*head_ref);    (*head_ref) = new_node;}Â
/* Utility function to print a singly linked list */void printList(struct Node *head){Â Â Â Â struct Node *temp = head;Â Â Â Â while (temp != NULL)Â Â Â Â {Â Â Â Â Â Â Â Â printf("(%d,%d)-> ", temp->x,temp->y);Â Â Â Â Â Â Â Â temp = temp->next;Â Â Â Â }Â Â Â Â printf("\n");Â
}Â
// Utility function to remove Next from linked list // and link nodes after it to headvoid deleteNode(struct Node *head, struct Node *Next){Â Â Â Â head->next = Next->next;Â Â Â Â Next->next = NULL;Â Â Â Â free(Next);}Â
// This function deletes middle nodes in a sequence of// horizontal and vertical line segments represented by// linked list.struct Node* deleteMiddle(struct Node *head){    // If only one node or no node...Return back    if (head==NULL || head->next ==NULL || head->next->next==NULL)        return head;Â
    struct Node* Next = head->next;    struct Node *NextNext = Next->next ;Â
    // Check if this is a vertical line or horizontal line    if (head->x == Next->x)    {        // Find middle nodes with same x value, and delete them        while (NextNext !=NULL && Next->x==NextNext->x)        {            deleteNode(head, Next);Â
            // Update Next and NextNext for next iteration            Next = NextNext;            NextNext = NextNext->next;        }    }    else if (head->y==Next->y) // If horizontal line    {        // Find middle nodes with same y value, and delete them        while (NextNext !=NULL && Next->y==NextNext->y)        {            deleteNode(head, Next);Â
            // Update Next and NextNext for next iteration            Next = NextNext;            NextNext = NextNext->next;        }    }    else // Adjacent points must have either same x or same y    {        puts("Given linked list is not valid");        return NULL;    }Â
    // Recur for next segment    deleteMiddle(head->next);Â
    return head;}Â
// Driver program to test above functionsint main(){Â Â Â Â struct Node *head = NULL;Â
    push(&head, 40,5);    push(&head, 20,5);    push(&head, 10,5);    push(&head, 10,8);    push(&head, 10,10);    push(&head, 3,10);    push(&head, 1,10);    push(&head, 0,10);    printf("Given Linked List: \n");    printList(head);Â
    if (deleteMiddle(head) != NULL);    {        printf("Modified Linked List: \n");        printList(head);    }    return 0;} |
Java
// Java program to remove middle points in a linked list of// line segments,class LinkedList{Â Â Â Â Node head;Â // head of listÂ
    /* Linked list Node*/    class Node    {        int x,y;        Node next;        Node(int x, int y)        {            this.x = x;            this.y = y;            next = null;        }    }Â
    // This function deletes middle nodes in a sequence of    // horizontal and vertical line segments represented    // by linked list.    Node deleteMiddle()    {        // If only one node or no node...Return back        if (head == null || head.next == null ||            head.next.next == null)            return head;Â
        Node Next = head.next;        Node NextNext = Next.next;Â
        // check if this is vertical or horizontal line        if (head.x == Next.x)        {            // Find middle nodes with same value as x and            // delete them.            while (NextNext != null && Next.x == NextNext.x)            {                head.next = Next.next;                Next.next = null;Â
                // Update NextNext for the next iteration                Next = NextNext;                NextNext = NextNext.next;            }        }Â
        // if horizontal        else if (head.y == Next.y)        {            // find middle nodes with same value as y and            // delete them            while (NextNext != null && Next.y == NextNext.y)            {                head.next = Next.next;                Next.next = null;Â
                // Update NextNext for the next iteration                Next = NextNext;                NextNext = NextNext.next;            }        }Â
        // Adjacent points should have same x or same y        else        {            System.out.println("Given list is not valid");            return null;        }Â
        // recur for other segmentÂ
        // temporarily store the head and move head forward.        Node temp = head;        head = head.next;Â
        // call deleteMiddle() for next segment        this.deleteMiddle();Â
        // restore head        head = temp;Â
        // return the head        return head;    }Â
    /* Given a reference (pointer to pointer) to the head        of a list and an int, push a new node on the front        of the list. */    void push(int x, int y)    {        /* 1 & 2: Allocate the Node &                  Put in the data*/        Node new_node = new Node(x,y);Â
        /* 3. Make next of new Node as head */        new_node.next = head;Â
        /* 4. Move the head to point to new Node */        head = new_node;    }Â
Â
    void printList()    {        Node temp = head;        while (temp != null)        {            System.out.print("("+temp.x+","+temp.y+")->");            temp = temp.next;        }        System.out.println();    }Â
Â
    /* Driver program to test above functions */    public static void main(String args[])    {        LinkedList llist = new LinkedList();Â
        llist.push(40,5);        llist.push(20,5);        llist.push(10,5);        llist.push(10,8);        llist.push(10,10);        llist.push(3,10);        llist.push(1,10);        llist.push(0,10);Â
        System.out.println("Given list");        llist.printList();Â
        if (llist.deleteMiddle() != null)        {            System.out.println("Modified Linked List is");            llist.printList();        }    }} /* This code is contributed by Rajat Mishra */ |
Python3
# Python program to remove middle points in a linked list of# line segments,class LinkedList(object):Â Â Â Â def __init__(self):Â Â Â Â Â Â Â Â self.head = NoneÂ
    # Linked list Node    class Node(object):        def __init__(self, x, y):            self.x = x            self.y = y            self.next = NoneÂ
    # This function deletes middle nodes in a sequence of    # horizontal and vertical line segments represented    # by linked list.    def deleteMiddle(self):        # If only one node or no node...Return back        if self.head == None or self.head.next == None or self.head.next.next == None:            return self.head        Next = self.head.next        NextNext = Next.next        # check if this is vertical or horizontal line        if self.head.x == Next.x:            # Find middle nodes with same value as x and            # delete them.            while NextNext != None and Next.x == NextNext.x:                self.head.next = Next.next                Next.next = None                # Update NextNext for the next iteration                Next = NextNext                NextNext = NextNext.next        elif self.head.y == Next.y:            # find middle nodes with same value as y and            # delete them            while NextNext != None and Next.y == NextNext.y:                self.head.next = Next.next                Next.next = None                # Update NextNext for the next iteration                Next = NextNext                NextNext = NextNext.next        else:            # Adjacent points should have same x or same y            print ("Given list is not valid")            return None        # recur for other segment        # temporarily store the head and move head forward.        temp = self.head        self.head = self.head.next        # call deleteMiddle() for next segment        self.deleteMiddle()        # restore head        self.head = temp        # return the head        return self.headÂ
    # Given a reference (pointer to pointer) to the head    # of a list and an int, push a new node on the front    # of the list.    def push(self, x, y):        # 1 & 2: Allocate the Node &        # Put in the data        new_node = self.Node(x, y)        # 3. Make next of new Node as head        new_node.next = self.head        # 4. Move the head to point to new Node        self.head = new_nodeÂ
    def printList(self):        temp = self.head        while temp != None:            print ("(" + str(temp.x) + "," + str(temp.y) + ")->",end=" ")            temp = temp.next        print ()Â
# Driver programllist = LinkedList()llist.push(40,5)llist.push(20,5)llist.push(10,5)llist.push(10,8)llist.push(10,10)llist.push(3,10)llist.push(1,10)llist.push(0,10)Â
print ("Given list")llist.printList()Â
if llist.deleteMiddle() != None:Â Â Â Â print ("Modified Linked List is")Â Â Â Â llist.printList()Â
# This code is contributed by BHAVYA JAIN |
C#
// C# program to remove middle// points in a linked list of// line segments,using System;Â
public class LinkedList{Â Â Â Â Node head; // head of listÂ
    /* Linked list Node*/    class Node    {        public int x,y;        public Node next;        public Node(int x, int y)        {            this.x = x;            this.y = y;            next = null;        }    }Â
    // This function deletes middle     // nodes in a sequence of horizontal and     // vertical line segments represented    // by linked list.    Node deleteMiddle()    {        // If only one node or no node...Return back        if (head == null || head.next == null ||            head.next.next == null)            return head;Â
        Node Next = head.next;        Node NextNext = Next.next;Â
        // check if this is vertical or horizontal line        if (head.x == Next.x)        {            // Find middle nodes with same            // value as x and delete them.            while (NextNext != null &&                     Next.x == NextNext.x)            {                head.next = Next.next;                Next.next = null;Â
                // Update NextNext for                // the next iteration                Next = NextNext;                NextNext = NextNext.next;            }        }Â
        // if horizontal        else if (head.y == Next.y)        {            // find middle nodes with same             // value as y and delete them            while (NextNext != null && Next.y == NextNext.y)            {                head.next = Next.next;                Next.next = null;Â
                // Update NextNext for the next iteration                Next = NextNext;                NextNext = NextNext.next;            }        }Â
        // Adjacent points should have same x or same y        else        {            Console.WriteLine("Given list is not valid");            return null;        }Â
        // recur for other segmentÂ
        // temporarily store the         // head and move head forward.        Node temp = head;        head = head.next;Â
        // call deleteMiddle() for next segment        this.deleteMiddle();Â
        // restore head        head = temp;Â
        // return the head        return head;    }Â
    /* Given a reference (pointer to pointer) to the head        of a list and an int, push a new node on the front        of the list. */    void push(int x, int y)    {        /* 1 & 2: Allocate the Node &                Put in the data*/        Node new_node = new Node(x,y);Â
        /* 3. Make next of new Node as head */        new_node.next = head;Â
        /* 4. Move the head to point to new Node */        head = new_node;    }Â
Â
    void printList()    {        Node temp = head;        while (temp != null)        {            Console.Write("("+temp.x + "," + temp.y + ")->");            temp = temp.next;        }        Console.WriteLine();    }Â
Â
    /* Driver code */    public static void Main(String []args)    {        LinkedList llist = new LinkedList();Â
        llist.push(40,5);        llist.push(20,5);        llist.push(10,5);        llist.push(10,8);        llist.push(10,10);        llist.push(3,10);        llist.push(1,10);        llist.push(0,10);Â
        Console.WriteLine("Given list");        llist.printList();Â
        if (llist.deleteMiddle() != null)        {            Console.WriteLine("Modified Linked List is");            llist.printList();        }    }}Â
// This code is contributed by Rajput-Ji |
Javascript
<script>Â
// Javascript program to remove middle // points in a linked list of// line segments,var head; // head of listÂ
    /* Linked list Node */    class Node {Â
constructor(x , y) {Â Â Â Â Â Â Â Â Â Â Â Â this.x = x;Â Â Â Â Â Â Â Â Â Â Â Â this.y = y;Â Â Â Â Â Â Â Â Â Â Â Â this.next = null;Â Â Â Â Â Â Â Â }Â Â Â Â }Â
    // This function deletes middle    // nodes in a sequence of    // horizontal and vertical line    // segments represented    // by linked list.    function deleteMiddle() {        // If only one node or no         // node...Return back        if (head == null || head.next == null ||        head.next.next == null)            return head;Â
var Next = head.next;var NextNext = Next.next;Â
        // check if this is vertical or        // horizontal line        if (head.x == Next.x) {            // Find middle nodes with same            // value as x and            // delete them.            while (NextNext != null &&             Next.x == NextNext.x)             {                head.next = Next.next;                Next.next = null;Â
                // Update NextNext for the next iteration                Next = NextNext;                NextNext = NextNext.next;            }        }Â
        // if horizontal        else if (head.y == Next.y) {            // find middle nodes with same value as y and            // delete them            while (NextNext != null &&             Next.y == NextNext.y) {                head.next = Next.next;                Next.next = null;Â
                // Update NextNext for the next iteration                Next = NextNext;                NextNext = NextNext.next;            }        }Â
        // Adjacent points should have same x or same y        else {            document.write("Given list is not valid");            return null;        }Â
        // recur for other segmentÂ
        // temporarily store the head and move head forward.var temp = head;        head = head.next;Â
        // call deleteMiddle() for next segment        this.deleteMiddle();Â
        // restore head        head = temp;Â
        // return the head        return head;    }Â
    /*     Given a reference (pointer to pointer) to      the head of a list and an int, push     a new node on the front of the list.     */    function push(x , y) {        /*         1 & 2: Allocate the Node & Put in the data         */var new_node = new Node(x, y);Â
        /* 3. Make next of new Node as head */        new_node.next = head;Â
        /* 4. Move the head to point to new Node */        head = new_node;    }Â
    function printList() {var temp = head;        while (temp != null) {            document.write("(" + temp.x + "," +             temp.y + ")->");            temp = temp.next;        }        document.write("<br/>");    }Â
    /* Driver program to test above functions */     Â
        push(40, 5);        push(20, 5);        push(10, 5);        push(10, 8);        push(10, 10);        push(3, 10);        push(1, 10);        push(0, 10);Â
        document.write("Given list<br/>");        printList();Â
        if (deleteMiddle() != null) {            document.write("Modified Linked List is<br/>");            printList();        }Â
// This code contributed by gauravrajput1Â
</script> |
Given Linked List: (0,10)-> (1,10)-> (3,10)-> (10,10)-> (10,8)-> (10,5)-> (20,5)-> (40,5)-> Modified Linked List: (0,10)-> (10,10)-> (10,5)-> (40,5)->
Time Complexity of the above solution is O(n) where n is a number of nodes in the given linked list.
Auxiliary Space: O(1) because it is using constant space
Exercise:Â
The above code is recursive, write an iterative code for the same problem. Please see below for the solution.
Iterative approach for removing middle points in a linked list of line segmentsÂ
Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 zambiatek!



