c语言快慢指针之找未知长度单链表中间结点的值并显示
程序员文章站
2023-08-29 19:00:16
快慢指针之找未知长度单链表中间结点的值并显示,希望下面的文章对大家有所帮助。
#include
#include
#include
#define max 5
typedef stru...
快慢指针之找未知长度单链表中间结点的值并显示,希望下面的文章对大家有所帮助。
#include #include #include #define max 5 typedef struct cursor { int data; struct cursor *next; }cursor; cursor *initlist(); void findlist(cursor head); void showlist(cursor head); void showlist(cursor head) { cursor *p; p=head.next; while(p!=null) { printf("%5d",p->data); p=p->next; } printf("\n"); } void findlist(cursor head) { cursor *mid; cursor *fast; cursor *p; fast=head.next; mid=head.next; while(fast->next!=null) { if(fast->next->next!=null) { fast=fast->next->next; mid=mid->next; } else { fast=fast->next; } } printf("%d",mid->data); } cursor *initlist() { cursor *head=null; cursor *p=null,*q=null; int k=0; head=(cursor *)(malloc(sizeof(cursor))); while(k { q=(cursor *)(malloc(sizeof(cursor))); k++; if(k==1) { head->next=q; } else { p->next=q; } p=q; p->data=rand()%100+1; } p->next=null; return head; } int main() { cursor *head=null; srand(time(null)); head=initlist(); showlist(*head); findlist(*head); }
上一篇: 姑娘你的奶