快慢指針
阿新 • • 發佈:2017-09-09
一個 中間 prev def fin void size return truct
//最快的方式查找一個鏈表中的最中間節點
#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; }
快慢指針