## C语言求链表长度（二级指针）

startstorm 发布于 2017/03/03 11:39

``````int ListLength01(LNode **p)	//求线性表的长度
{
if (p == NULL)
{
return -1;
}
static int count = 0;
LNode **tmp = p;
while ((*tmp)->next != NULL)
{
(*tmp) = (*tmp)->next;
++count;
}
return count;
}``````

``````int ListLength02(LNode **p)	//求线性表的长度
{
if (p == NULL)
{
return -1;
}
static int count = 0;
LNode *tmp = *p;
while (tmp->next != NULL)
{
tmp = tmp->next;
++count;
}
return count;
}``````

``````#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <stdlib.h>
#define flag -1
typedef struct LNode
{
int data;
struct LNode *next;
}LNode;

{
if (L == NULL)
{
return -1;
}
LNode *r, *s;
int x;
scanf("%d", &x);
r = *L;
while (x != flag)
{
s = (LNode *)malloc(sizeof(LNode));
s->data = x;
r->next = s;
r = s;
scanf("%d", &x);
}
r->next = NULL;
return 0;
}

{
if (L == NULL)
{
return -1;
}
LNode *p = (*L)->next;
while (p != NULL)
{
printf("%d---", p->data);
p = p->next;
}
printf("\n");
return 0;
}

int ListLength01(LNode **p)	//求线性表的长度
{
if (p == NULL)
{
return -1;
}
static int count = 0;
LNode *tmp = *p;
while (tmp->next != NULL)
{
tmp = tmp->next;
++count;
}

//LNode **tmp = p;
//while ((*tmp)->next != NULL)
//{
//	(*tmp) = (*tmp)->next;
//	++count;
//}
return count;
}

int GetElem(LNode **p, int i, int *e)	//取L1中第i个元素赋值给e
{
if (p == NULL)
{
return -1;
}
LNode *r;
r = *p;
static int count;
while (r!=NULL && count<i)
{
++count;
r = r->next;
}
*e = r->data;
return 0;
}

int main()
{
LNode *L;
int i = 0;
int e = 0;
int q = 2;
L = (LNode *)malloc(sizeof(LNode));
L->next = NULL;
printf("\n");

i = ListLength01(&L);
printf("%d\n", i);

printf("\n");
GetElem(&L, q, &e);
printf("%d\n", e);
return 0;
}
``````

0

0

#### 引用来自“GestureWei”的评论

static可以理解为局部可见性的全局变量，生命期是跟随整个进程的

0
``````int ListLength01(LNode **p)	//求线性表的长度
``````

* 就是为了跳过只能传值的限制。**p就是为了修改*p