问题:链表长度未知,如何查找中间节点
分析:链表中间节点受链表长度影响,奇数长度如abc则中间节点为b,偶数长度如abcd则中间节点为bc。
解决方法:使用两个指针ptr1 = ptr2 =head,同时遍历链表,ptr1步长为1,ptr2步长为2.当ptr2到达链表尾时,ptr1即为中间节点(如果链表长为偶数,则ptr1->next也是中间节点)。
代码如下:
#include<stdio.h>
typedef struct node
{
int data;
struct node *next;
}NODE;
NODE* create_list(int num)
{
NODE *head = NULL;
NODE *cur = NULL;
int i = 0;
if (num <= 0)
return NULL;
while( i++ < num )
{
NODE *tmp = (NODE*)malloc(sizeof(NODE));
tmp->data = i;
tmp->next = NULL;
if ( i == 1)
{
head = tmp;
}
else
{
cur->next = tmp;
}
cur = tmp;
}
return head;
}
void print_list(NODE *head)
{
printf("List:\n");
while(head != NULL)
{
printf("%d\t", head->data);
head = head->next;
}
printf("\n");
}
void search_middle_node(NODE *head)
{
NODE *single_step = head;
NODE *double_step = head;
while(double_step != NULL)
{
if ( double_step->next == NULL )
{
printf("Middle Node :%d\n", single_step->data);
return;
}
if ( double_step->next->next == NULL)
{
printf("Middle Node :%d\t%d\n", single_step->data, single_step->next->data);
return;
}
single_step = single_step->next;
double_step = double_step->next->next;
}
return;
}
void main(){
NODE *head = create_list(5);
print_list(head);
search_middle_node(head);
}