快慢指针

//最快的方式查找一个链表中的最中间节点
#include<stdio.h> #define SIZE 100000 typedef struct Node{ int data; struct Node* next; struct Node* prev; }Node; Node f[SIZE]; int index = 0; Node* head; Node* getnode(){ return &f[index++]; } void init(){ index = 0; head = getnode(); head->prev = head; head->next = head; head->data = -1; } void InsertAfter(Node*dst,Node*newnode){ newnode->prev = dst; newnode->next = dst->next; dst->next->prev = newnode; dst->next = newnode; } int main(){ init(); Node* temp = getnode();//head的地址要保存下来用于遍历 for(int i=1;i<21;i++){ Node* p = getnode(); p->data = i; if(i==1){temp = head;} else{temp=temp->next;} InsertAfter(temp,p); } Node* p1,*p2;//快慢指针 p1 = head->next; p2 = head->next; while(p1->data!=-1){ p1 = p1->next->next; p2 = p2->next; } printf("%d ",p2->prev->data); return 0; }
大多数想法要么平庸,要么更糟糕,这很大程度上因为绝妙的想法难得一见,而且他们还要在我们身边这个充斥了各种恶俗的所谓常识的环境中孕育生长。
原文地址:https://www.cnblogs.com/linux0537/p/7496926.html