1. 使用两个指针进行遍历,快指针每次步进2,慢指针每次步进1.
2. 当快指针到达链表尾部的时候,慢指针指向的就是链表的中点.
代码:
//linked.c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct node {
int data;
struct node *next;
} Node;
Node *initLink(int num){
Node *head = (Node *)malloc(sizeof(Node));
head->data = -1;
head->next = NULL;
Node *tmp = head;
int i = 0;
for(i=0; i < num; i++){
Node *one = (Node *)malloc(sizeof(Node));
one->data = i;
tmp = tmp->next = one;
}
return head;
}
Node *search(Node *head){
if(NULL == head || NULL == head->next || NULL == head->next->next)
return head;
int a = 0;
Node *mid = head;
Node *last = mid->next;
while(NULL != last && NULL != last->next){
mid = mid->next;
last = last->next->next;
}
return mid;
}
void print(const Node *head){
while(head != NULL){
printf("%d\n", head->data);
head = head->next;
}
}
int main(int argc, char *argv[]){
Node *n = initLink(10);
print(n);
Node *mid = search(n);
printf("the mid node is %d\n", mid->data);
2. 当快指针到达链表尾部的时候,慢指针指向的就是链表的中点.
代码:
//linked.c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct node {
int data;
struct node *next;
} Node;
Node *initLink(int num){
Node *head = (Node *)malloc(sizeof(Node));
head->data = -1;
head->next = NULL;
Node *tmp = head;
int i = 0;
for(i=0; i < num; i++){
Node *one = (Node *)malloc(sizeof(Node));
one->data = i;
tmp = tmp->next = one;
}
return head;
}
Node *search(Node *head){
if(NULL == head || NULL == head->next || NULL == head->next->next)
return head;
int a = 0;
Node *mid = head;
Node *last = mid->next;
while(NULL != last && NULL != last->next){
mid = mid->next;
last = last->next->next;
}
return mid;
}
void print(const Node *head){
while(head != NULL){
printf("%d\n", head->data);
head = head->next;
}
}
int main(int argc, char *argv[]){
Node *n = initLink(10);
print(n);
Node *mid = search(n);
printf("the mid node is %d\n", mid->data);
}
http://blog.163.com/cross_liu/blog/static/200289195200963005459975/