//最快的方式查找一个链表中的最中间节点#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\n",p2->prev->data); return 0; }
时间: 2024-10-15 17:35:43