题目:建立单链表并找到中间数
普通方法就是先遍历一遍链表知道了单链表的长度N,然后再从头找到N/2时候的数。这种方法时间复杂度为O(N+N/2)=O(3N/2)。
在优化一下这个方法,可以利用快慢指针,也就是设置两个指针,然后快的一次移动两个,慢的一次移动一个位置。总体代码(C语言):
#include<stdio.h>
#include<stdlib.h>
#include<time.h>
struct Node{
int num;
struct Node * next;
};
struct Node * create(struct Node *,int a);
void getmid(struct Node *,int);
int main(){
struct Node * head=NULL,* p;
int n=20,a;
head=create(head,n);
if(head==NULL){
printf("error\n");
exit(0);
}
p=head;
while(p->next){
printf("%d\n",p->num);
p=p->next;
}
getmid(head,a);
return 0;
}
struct Node * create(struct Node * head,int n){ //建立链表
struct Node * q,* newnode;
int i;
newnode=(struct Node *)malloc(sizeof(struct Node));
newnode->num=rand()%100+1;
head=q=newnode;
srand(time(0));
for(i=0;i<n;i++){
newnode=(struct Node *)malloc(sizeof(struct Node));
newnode->num=rand()%100+1; //随机1到100
q->next=newnode;
q=q->next;
}
q->next=NULL;
return head;
}
void getmid(struct Node * head,int a){
struct Node * search,* mid;
search=mid=head;
while(search->next){
if(search->next->next){
search=search->next->next;
mid=mid->next;
}
else{
search=search->next;
}
}
a=mid->num;
printf("中间数%d",a);
}