# 面试题10：查找单链表的中间结点,面试题9：单链表中倒数第k个结点

```/*     获取链表的中间结点    */
{
Node *p1, *p2;

while(1)
{
if(p1->next != NULL && p1->next->next != NULL)
{
p1 = p1->next->next;
p2 = p2->next;
}
else
break;
}
return p2;
}```

```#include<iostream>
#include <stack>
#include<stdlib.h>
#include<time.h>

using namespace std;

typedef struct node
{
int data;
struct node *next;
}Node;

/*     创建含有n个结点的单链表    */
{

/* 初始化随机数种子 */
srand(time(0));  //srand函数在stdlib.h头文件中，time函数在time.h头文件中

for(int i=0; i < n; i++)
{
Node *p = (Node *)malloc(sizeof(Node));
p->data = rand()%100+1;  //随机生成100以内的数字
p->next = q->next;
q->next = p;
q = p;
}
q->next = NULL;

}

/****打印单链表******/
{
Node *p;
{
cout << "The LinkList is Empty !" <<endl;
return;
}
while(p!=NULL)
{
cout << p->data << " " ;
p=p->next;
}
}
/*     获取链表的中间结点    */
{
Node *p1, *p2;

while(1)
{
if(p1->next != NULL && p1->next->next != NULL)
{
p1 = p1->next->next;
p2 = p2->next;
}
else
break;
}
return p2;
}
int main()
{
int length;

cin >> length;
cout << "The new created LinkList as below: " ;
cout << endl;

Node *midNode = NULL;