新德里机场免税店攻略:怎么求单链表的长度?有没有C的源代码?

来源:百度文库 编辑:杭州交通信息网 时间:2024/05/09 11:10:08
int Listlength(Linklist L) //求链表长度
{
Linklist p;
int j=0;
p=L;
while(p->next!=NULL)
{
++j;
p=p->next;
}
return j;
}

这个求长度函数有点问题?

int Listlength(Linklist *L) //求链表长度
{
node *p; //链表的单个元素指针,而不能用链表
int j=0;
p=L; //将其指向链表的第一个元素
while(p->next!=NULL)
{
++j;
p=p->next;
}
return j;
}

// 楼上的解答有误!

// xssd.cpp : Defines the entry point for the console application.
//

#include "stdafx.h"
#include<stdlib.h>
#include<stdio.h>
#include<malloc.h>

typedef struct Linklist{
int i;
Linklist *next;
};

int Listlength(Linklist *L) //求链表长度
{
Linklist *p; // ?????链表的单个元素指针,而不能用链表

int j=0;
p=L;
while(p->next!=NULL)
{
++j;
p=p->next;
}
return j+1; //
}

int _tmain(int argc, _TCHAR* argv[])
{ //创建一个链表
Linklist * L;
L = (Linklist *)malloc(sizeof(Linklist));
L->i = 100;
L->next = NULL;

//计算链表长度
int LL = Listlength(L);
printf("%d",LL);
system("pause");
return 0;
}