How to find the middle node of a single linked list in a single traversal (if the length of the list is not given)

心已入冬 提交于 2019-12-03 20:21:43

Following are the steps:

  • Take two pointers *p1 and *p2 pointing to the head of linked list
  • Start a loop and increment *p2, 2 times (with null checks)
  • If *p2 is not null then increment *p1 1 time
  • When *p2 reaches null; you have got the *p1 at the center

[Note: You can use iterators instead of pointer if you deal with container type linked list]

Say you have a std::list<T> l.

std::list<T>::iterator i = l.begin();
std::list<T>::iterator m = l.begin();
bool even = true;
while (i != list.end())
{
  if (even) ++m;
  ++i;
  even = !even;
}

Now m point to the middle of l.

You can use a single loop with two iterators, say it1 and it2, where you increment it2 only every second iteration of the loop. Terminate when it1 has reached the end of the list. it2 will now point to the middle element of the list.

Try this:
You have 2 pointers. one points to mid, and the other to the end, both point to beginning of the list at start. Every second time you successfully increment the end pointer you increment mid a once, until you end pointer reaches the end.

Use two pointers. Move first pointer by two nodes and second pointer by one node. When the first pointer reaches the end the second pointer will point to the middle.

// How to find the middle node of a single linked list in a single traversal
//     1. The length of the list is not given
//     2. If the number of nodes is even, there are two middle nodes,
//        return the first one.
Node* MiddleNode(Node* const head)
{
    if (!head)
    {
        return head;
    }

    Node* p1 = head, * p2 = head->next;

    while (p2 && p2->next)
    {
        p1 = p1->next;
        p2 = p2->next->next;
    }

    return p1;
}
RajatRusty
SLNode* mid(SLNode *head) 

{

SLNode *one = head;

SLNode *two = head;


    while(one != nullptr) {
        one = one->next;
        two = two->next;
        if(one != nullptr) {
            one = one->next;
            //two = two->next;
        }
    }
    return two;
}

try this code

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!