Application of the speed of interview questions Tencent pointer

Application of the speed of interview questions Tencent pointer

Demand value chain intermediate node (node ​​points where the number of parity)

(. 1) MID and search (search pointer, the pointer fast)
(2) Search is twice the moving speed of the mind (thought scale)

#include <iostream>

using namespace std;

//增强代码的可读性,状态值设置为Status
typedef int Status;
typedef double ElemType;

//Status状态中OK为1,ERROR为0
#define OK 1
#define ERROR 0

/**
 * 节点的声明
 */
typedef struct node {
    //数据data
    double data;
    struct node* next;
}LinkList;

/**
 * 获得中间结点,将其值赋予e
 * @param L 单向链表
 * @param e 存储器(存储中间结点值)
 * @return 状态值
 */
Status getMidNode(LinkList* L, ElemType* e) {
    //赋初值都指向开头
    LinkList* mid, *search;
    mid = search = L;
    
    //开始遍历至最后一个结点
    while(search->next != NULL) {
        //色arch是mid速度的两倍
        //跳两次是空
        if(search->next->next != NULL) {
            search = search->next->next;
            mid = mid->next;
        } else {
            search = search->next;
        }
        
    }//of search->next
    
    *e = mid->data;//此时search为最后一个结点,mid为中间结点
    return OK;//结束
}

Development: to determine whether there is a one-way chain rings?

(1) with two list head pointer to each cycle, two steps forward pointer fast, slow pointer forward one step;
(2) during the cycle, if the pointer is equal to slow the fast pointer (met), it means that there is a linked list ring; otherwise there is no ring.

How to calculate the length of the loop?

(1) at the meeting point, a continue step by two pointers, a take two steps, when the meet again, step by the number of nodes traversed by the pointer mark length of the ring.

Published 47 original articles · won praise 18 · views 4856

Guess you like

Origin blog.csdn.net/qq_43605085/article/details/103047028