Advertisement
jayati

Delete the Middle Node of a Linked List

May 7th, 2024
536
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.07 KB | None | 0 0
  1. /**
  2.  * Definition for singly-linked list.
  3.  * struct ListNode {
  4.  *     int val;
  5.  *     ListNode *next;
  6.  *     ListNode() : val(0), next(nullptr) {}
  7.  *     ListNode(int x) : val(x), next(nullptr) {}
  8.  *     ListNode(int x, ListNode *next) : val(x), next(next) {}
  9.  * };
  10.  */
  11. class Solution {
  12. public:
  13.     ListNode* deleteMiddle(ListNode* head) {
  14.         if(head->next==NULL)
  15.         {
  16.             return NULL;
  17.         }
  18.         ListNode* temp = head;
  19.         int l=0;
  20.         while(temp->next!=NULL)
  21.         {
  22.             l++;
  23.             temp=temp->next;
  24.         }
  25.         // if(l%2==1)
  26.         // {
  27.         //    l=l/2;
  28.         // }
  29.         // else
  30.         // {
  31.         //     l=(l/2)+1;
  32.         // }
  33.         int i=0;
  34.         ListNode* prev=NULL;
  35.         ListNode* curr=head;
  36.         while(i<((l+1)/2))
  37.         {
  38.             prev=curr;
  39.              curr=curr->next;
  40.             i++;
  41.         }
  42.         // ListNode* curr=prev->next;
  43.         prev->next=curr->next;
  44.         curr->next=NULL;
  45.         delete(curr);
  46.         return head;
  47.        
  48.     }
  49. };
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement