Skip to content
geeksforgeeks
  • 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
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • 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:
C++ Program For Printing Nth Node From The End Of A Linked List
Next article icon

C++ Program For Removing Middle Points From a Linked List Of Line Segments

Last Updated : 21 Aug, 2022
Comments
Improve
Suggest changes
Like Article
Like
Report

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;          }      }       // If horizontal line      else if (head->y == Next->y)      {          // 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;          }      }       // Adjacent points must have either      // same x or same y      else      {          puts("Given linked list is not valid");          return NULL;      }       // Recur for next segment      deleteMiddle(head->next);       return head;  }   // Driver code 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: ";      printList(head);       if (deleteMiddle(head) != NULL);      {          cout << "Modified Linked List: ";          printList(head);      }      return 0;  }  // This is code is contributed by rathbhupendra 

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 of the above solution is O(n) where n is a number of nodes in the given linked list.

Auxiliary Space: O(1)
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 Please refer complete article on Given a linked list of line segments, remove middle points for more details!


Next Article
C++ Program For Printing Nth Node From The End Of A Linked List
author
kartik
Improve
Article Tags :
  • Linked List
  • C++ Programs
  • DSA
  • Linked Lists
Practice Tags :
  • Linked List

Similar Reads

  • C++ Program For Removing Every K-th Node Of The Linked List
    Given a singly linked list, Your task is to remove every K-th node of the linked list. Assume that K is always less than or equal to length of Linked List.Examples : Input: 1->2->3->4->5->6->7->8 k = 3 Output: 1->2->4->5->7->8 As 3 is the k-th node after its deletion list would be 1->2->4->5->6->7->
    3 min read
  • C++ Program For Inserting Node In The Middle Of The Linked List
    Given a linked list containing n nodes. The problem is to insert a new node with data x at the middle of the list. If n is even, then insert the new node after the (n/2)th node, else insert the new node after the (n+1)/2th node. Examples: Input : list: 1->2->4->5 x = 3 Output : 1->2->
    5 min read
  • C++ Program For Printing Nth Node From The End Of A Linked List
    Given a Linked List and a number n, write a function that returns the value at the n'th node from the end of the Linked List.For example, if the input is below list and n = 3, then output is "B" Recommended: Please solve it on "PRACTICE" first, before moving on to the solution. Method 1 (Use length
    4 min read
  • C++ Program For Removing Duplicates From A Sorted Linked List
    Write a function that takes a list sorted in non-decreasing order and deletes any duplicate nodes from the list. The list should only be traversed once. For example if the linked list is 11->11->11->21->43->43->60 then removeDuplicates() should convert the list to 11->21->43-
    9 min read
  • C++ Program For Removing Duplicates From An Unsorted Linked List
    Write a removeDuplicates() function that takes a list and deletes any duplicate nodes from the list. The list is not sorted. For example if the linked list is 12->11->12->21->41->43->21 then removeDuplicates() should convert the list to 12->11->21->41->43. Recommended:
    4 min read
  • C++ Program For Removing All Occurrences Of Duplicates From A Sorted Linked List
    Given a sorted linked list, delete all nodes that have duplicate numbers (all occurrences), leaving only numbers that appear once in the original list. Examples: Input: 23->28->28->35->49->49->53->53 Output: 23->35 Input: 11->11->11->11->75->75 Output: empty Li
    4 min read
  • C++ 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->5 If there are even nodes, then there would be two middle nodes, we need to delete the second middle element. For example, if g
    4 min read
  • C++ Program For Writing A Function To Get Nth Node In A Linked List
    Write a C++ Program to GetNth() function that takes a linked list and an integer index and returns the data value stored in the node at that index position. Example: Input: 1->10->30->14, index = 2Output: 30 The node at index 2 is 30Recommended: Please solve it on "PRACTICE" first, before m
    4 min read
  • C++ Program For Making Middle Node Head In A Linked List
    Given a singly linked list, find middle of the linked list and set middle node of the linked list at beginning of the linked list. Examples: Input: 1 2 3 4 5 Output: 3 1 2 4 5 Input: 1 2 3 4 5 6 Output: 4 1 2 3 5 6 The idea is to first find middle of a linked list using two pointers, first one moves
    3 min read
  • C++ Program For Rearranging A Given Linked List In-Place
    Given a singly linked list L0 -> L1 -> … -> Ln-1 -> Ln. Rearrange the nodes in the list so that the new formed list is : L0 -> Ln -> L1 -> Ln-1 -> L2 -> Ln-2 ...You are required to do this in place without altering the nodes' values. Examples: Input: 1 -> 2 -> 3 -
    7 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