Fast and slow pointers in the linked list

Topic: A singly linked list L with a head node, design an algorithm that is as efficient as possible, and find the intermediate nodes in L

Idea: Fast and slow pointers

Define two pointers, where the fast pointer takes two steps and the slow pointer takes one step. When the fast pointer points to the end, the slow pointer just points to the middle node

(Big frog means fast pointer, small frog means slow pointer)

The code is implemented as follows:

#include<iostream>
#include<string>
using namespace std;

typedef struct LNode{
    int data;
    struct LNode *next;
}LNode,*LinkList;

//使用头插法创建单链表,注意创建链表的时候需要&符号
void CreatList_R(LinkList &L)
{
    int n;
    LinkList s,r;
    L = new LNode;
    L->next = NULL;
    r = L;
    cout << "请输入元素的个数:" << endl; 
    cin >> n;
    while (n--)
    {
        s = new LNode;
        cin >> s->data;
        r -> next = s;
        r = s;
    }
}

LinkList FindMid(LinkList L)
{
    //定义快指针p,慢指针q
    LinkList p,q;
    p = L;
    q = L;
    //如果p->next = NULL,不存在p->next->next
    while (p != NULL && p->next != NULL)
    {
        p = p->next->next;
        q = q->next;
    }
    //返回中间结点
    return q;
}

//单链表的输出
void ListPrint_L(LinkList L)
{
    LinkList p;
    p = L->next;
    while(p)
    {
        cout << p->data << endl;
        p = p->next;
    }
}

int main()
{
    LinkList L,mid;
    CreatList_R(L);
    mid = FindMid(L);
    cout << "中间元素为:" << mid->data << endl;
    return 0;
}

 operation result:

 

Guess you like

Origin blog.csdn.net/smallrain6/article/details/106186987