快慢指针查找未知长度单链表中间值
快慢指针查找位置长度的单链表的中间值。。。。
根据步长不同,也可以用来查找三分之一处,四分之一处。。。。。。
typedef struct List { int data; struct List * next; }List; void list_init(List *head, const int len); void search(List *head); void list_print(List *head); void list_des(List *head); int main() { int len = 0; List head = {0, NULL}; printf("输入长度:"); scanf("%d", &len); list_init(&head, len); list_print(&head); search(&head); list_des(&head); return 0; } void list_init(List *head, const int len) { int i = 0; List *p = head; for(i=0; i<len; i++) { p->next = (List *)malloc(sizeof(List)); p = p->next; p->data = i+1; p->next = NULL; } } void search(List *head) { List *search = head; List *middle = head; while(search) { if(search->next) { search = search->next->next; }else { search = search->next; } middle = middle->next; } printf("middle data: %d\n", middle->data); } void list_print(List *head) { List *p = head; while(p->next) { p = p->next; printf("%d ", p->data); } printf("\n"); } void list_des(List *head) { List *p = head->next; List *q = NULL; while(p) { q = p->next; free(p); p = q; } head->next = NULL; }