查找在鏈表中間的元素我寫了下面的函數返回一個鏈表的中間元素,它採用了雙指針方法使用雙指針法
struct node
{
int data;
struct node *next;
}*start;
void middleelement()
{
struct node *x=start,*y=start;
int n=0;
if(start==NULL)
{
printf("\nThere are no elments in the list");
}
else
{
while((x->next)!=NULL)
{
x=x->next->next;
y=y->next;
n++;
}
printf("\nMiddle element is %d",y->data);
}
}
但是,每當我運行的功能,Windows資源管理器停止工作 代碼中的缺陷是什麼? 有沒有比這更好的算法來找到中間元素?
如果列表中有奇數個元素,該怎麼辦? – pmg 2012-07-13 15:49:16
這聞起來像作業... – Keplah 2012-07-13 15:54:51
如果'x = x-> next-> next;'等於null? – 2012-07-13 15:57:28