jayati

Middle of the Linked List

Mar 17th, 2023
221
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 0.75 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.     int finleng(ListNode* head)
  14.     {
  15.         ListNode* tmp = head;
  16.         int c=0;
  17.         while(tmp!=nullptr)
  18.         {
  19.             c++;
  20.             tmp=tmp->next;
  21.         }
  22.         return c;
  23.     }
  24.     ListNode* middleNode(ListNode* head) {
  25.         int l=finleng(head);
  26.         ListNode* temp = head;
  27.         int nl = l/2;
  28.         for(int i=0;i<nl;i++)
  29.         {
  30.             temp=temp->next;
  31.         }
  32.  
  33.         return temp;
  34.     }
  35. };
Advertisement
Add Comment
Please, Sign In to add comment