设计一个计算单链表(链表带头结点)中结点个数的算法,并依此输出链表中的元素的值

2024-11-15 13:39:28
推荐回答(2个)
回答1:

#include
#include
typedef struct node
{
int data;
struct node *next;
}node;
void count(node* l)//计算节点个数,输出所有值
{
int n = 0;
node* p = l->next;
while(p)
{
printf("%d ",p->data);
p = p->next;
n++;
}
printf("\n%d\n",n);
}
int main()
{
int e;
//头节点
node *head,*p,*q;
head = (node*)malloc(sizeof(node));
head->next = NULL;
p = head;
printf("输入元素,回车结束:");
do{
scanf("%d",&e);
q = (node*)malloc(sizeof(node));
q->data = e;
q->next = NULL;
p->next = q;
p = q;
}while(getchar()!='\n');
count(head);
return 0;
}

回答2:

我无语了,还有比这更简单的功能么,学习你就看看数据结构呗,上网多浪费时间