Skip to content
geeksforgeeks
  • Tutorials
    • Python
    • Java
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
    • Practice Coding Problems
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • DSA
  • Interview Problems on Linked List
  • Practice Linked List
  • MCQs on Linked List
  • Linked List Tutorial
  • Types of Linked List
  • Singly Linked List
  • Doubly Linked List
  • Circular Linked List
  • Circular Doubly Linked List
  • Linked List vs Array
  • Time & Space Complexity
  • Advantages & Disadvantages
Open In App
Next Article:
Iterative approach for removing middle points in a linked list of line segments
Next article icon

Iterative approach for removing middle points in a linked list of line segments

Last Updated : 27 Jan, 2023
Comments
Improve
Suggest changes
Like Article
Like
Report

This post explains the iterative approach of this problem. 

We maintain two pointers, prev and temp. If these two have either x or y same, we move forward till the equality holds and keep deleting the nodes in between. The node from which the equality started, we adjust the next pointer of that node.

Implementation:

C++
// C++ program to remove intermediate  // points in a linked list that represents // horizontal and vertical line segments #include <iostream> using namespace std;  // Node has 3 fields including x, y // coordinates and a pointer to next node struct 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 = 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(struct Node *head) {     struct Node *temp = head;         while (temp != NULL) {         printf("(%d, %d)-> ", temp->x, temp->y);                 temp = temp->next;     }         printf("\n"); }  // This function deletes middle nodes in a  // sequence of horizontal and vertical line  // segments represented by linked list. void delete_Middle_Nodes(Node *head)  {         Node *temp = head->next, *prev = head;          while (temp) {                  // checking equality of point x         if (temp->x == prev->x)          {             Node *curr = prev;             prev = temp;             temp = temp->next;                                  // removing vertical points of line              // segment from linked list             while (temp && temp->x == prev->x)              {                 curr->next = temp;                 free(prev);                 prev = temp;                 temp = temp->next;             }         }          // checking equality of point y         else if (temp->y == prev->y)          {             Node *curr = prev;             prev = temp;             temp = temp->next;                          // removing horizontal points of line              // segment from linked list             while (temp && temp->y == prev->y)             {                 curr->next = temp;                 free(prev);                 prev = temp;                 temp = temp->next;             }         } else {             prev = temp;             temp = temp->next;         }     } }  // Driver program to test above functions int 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);          delete_Middle_Nodes(head);          printf("Modified Linked List: \n");     printList(head);          return 0; } 
Java
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.     private void delete_Middle_Nodes(Node head)     {         Node prev = head;         Node temp = head.next;          while (temp != null)         {              // checking equality of point x             if (temp.x == prev.x)             {                 Node curr = prev;                 prev = temp;                 temp = temp.next;                  // removing vertical points of line                  // segment from linked list                 while (temp != null && temp.x == prev.x)                 {                     curr.next = temp;                     prev.next = null;                     prev = temp;                     temp = temp.next;                 }             }              // checking equality of point y              else if (temp.y == prev.y)             {                 Node curr = prev;                 prev = temp;                 temp = temp.next;                  // removing horizontal points of line                  // segment from linked list                 while (temp != null && temp.y == prev.y)                 {                     curr.next = temp;                     prev.next = null;                     prev = temp;                     temp = temp.next;                 }             }              else             {                 prev =temp;                 temp = temp.next;             }         }     }      /* 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 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);          System.out.println("Given list");         llist.printList();          llist.delete_Middle_Nodes(llist.head);          System.out.println("Modified Linked List is");         llist.printList();     } }  // This code is contributed by shubham96301. 
Python3
# 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 
C#
// C# program to remove intermediate  // points in a linked list that represents // horizontal and vertical line segments using System;      public class LinkedList {     public Node head; // head of list      /* Linked list Node*/     public 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.     private void delete_Middle_Nodes(Node head)     {         Node prev = head;         Node temp = head.next;          while (temp != null)         {              // checking equality of point x             if (temp.x == prev.x)             {                 Node curr = prev;                 prev = temp;                 temp = temp.next;                  // removing vertical points of line                  // segment from linked list                 while (temp != null && temp.x == prev.x)                 {                     curr.next = temp;                     prev.next = null;                     prev = temp;                     temp = temp.next;                 }             }              // checking equality of point y              else if (temp.y == prev.y)             {                 Node curr = prev;                 prev = temp;                 temp = temp.next;                  // removing horizontal points of line                  // segment from linked list                 while (temp != null && temp.y == prev.y)                 {                     curr.next = temp;                     prev.next = null;                     prev = temp;                     temp = temp.next;                 }             }              else             {                 prev =temp;                 temp = temp.next;             }         }     }      /* 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();          llist.delete_Middle_Nodes(llist.head);          Console.WriteLine("Modified Linked List is");         llist.printList();     } }  /* This code contributed by PrinciRaj1992 */ 
JavaScript
<script>  // JavaScript program to remove intermediate  // points in a linked list that represents // horizontal and vertical line segments  var head = null; // 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 delete_Middle_Nodes(head) {     var prev = head;     var temp = head.next;     while (temp != null)     {         // checking equality of point x         if (temp.x == prev.x)         {             var curr = prev;             prev = temp;             temp = temp.next;             // removing vertical points of line              // segment from linked list             while (temp != null && temp.x == prev.x)             {                 curr.next = temp;                 prev.next = null;                 prev = temp;                 temp = temp.next;             }         }         // checking equality of point y          else if (temp.y == prev.y)         {             var curr = prev;             prev = temp;             temp = temp.next;             // removing horizontal points of line              // segment from linked list             while (temp != null && temp.y == prev.y)             {                 curr.next = temp;                 prev.next = null;                 prev = temp;                 temp = temp.next;             }         }          else         {             prev =temp;             temp = temp.next;         }     } } /* 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 code */ 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(); delete_Middle_Nodes(head); document.write("Modified Linked List is:<br>"); printList();  </script> 

Output
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: O(N) where N is no of nodes in given linked list

Auxiliary Space: O(1)


Next Article
Iterative approach for removing middle points in a linked list of line segments

E

Ekta Goel
Improve
Article Tags :
  • Linked List
  • DSA
  • Linked Lists
Practice Tags :
  • Linked List

Similar Reads

    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: Linke
    14 min read
    Javascript Program For Removing Middle Points From a Linked List Of Line Segments
    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
    4 min read
    Remove all occurrences of one Linked list in another Linked list
    Given two linked lists head1 and head2, the task is to remove all occurrences of head2 in head1 and return the head1. Examples: Input: head1 = 2 -> 3 -> 4 -> 5 -> 3 -> 4, head2 = 3 -> 4Output: 2 -> 5Explanation: After removing all occurrences of 3 -> 4 in head1 output is 2 -
    9 min read
    Find middle point segment from given segment lengths
    Given an array arr[] of size M. The array represents segment lengths of different sizes. These segments divide a line beginning with 0. The value of arr[0] represents a segment from 0 arr[0], value of arr[1] represents segment from arr[0] to arr[1], and so on. The task is to find the segment which c
    6 min read
    Javascript Program To Delete Middle Of Linked List
    Given a singly linked list, delete the middle of the linked list. For example, if the given linked list is 1->2->3->4->5 then the linked list should be modified to 1->2->4->5If there are even nodes, then there would be two middle nodes, we need to delete the second middle elemen
    3 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences