問題:鏈表長度未知,如何查找中間節點
分析:鏈表中間節點受鏈表長度影響,奇數長度如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);
}