请编写一个完整的程序
1.计算单链表的长度,并将结果存放在头节点的数据域中,然后输出单链表。(在下面的代码中应该怎么做?)
#include<stdio.h>
#include<stdlib.h>
#include<time.h>
struct Node{
int Data;
struct Node*Next;
};
void Print(struct Node *L){
struct Node *q;
q=L->Next;
while(q!=NULL){
printf("%d ",q->Data);
q=q->Next;
}
}
void Insert(struct Node*L,int n){ //插入数据
struct Node*p,*q;
p=L;
q=(struct Node*)malloc(sizeof(struct Node));
while(p->Next!=NULL&&p->Next->Data<n){
p=p->Next;
}
q->Data=n;
q->Next=p->Next;
p->Next=q;
}
void length(Node *L) //计算单链表长度
{
Node *p;
*p=*L->Next;
int j=0;
while(p!=NULL)
{
p=p->Next;
j++;
}
printf("%d",j); //为什么在运行结果中无法显示?
printf("\n");
}
int main(){
struct Node *L;
L=(struct Node*)malloc(sizeof(struct Node));
L->Next=NULL;
srand((int)time(NULL));
int i;
for(i=1;i<20;i++){
Insert(L,rand()%200);
}
Print(L);
return 0;
}
主要是
*p = *L->Next;
写错了,应该是
p = L->Next;
length(struct Node *L)函数没有调用啊
你题目的解答代码如下:(如有帮助,望采纳!谢谢! 点击我这个回答右上方的【采纳】按钮)
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
struct Node
{
int Data;
struct Node *Next;
};
void Print(struct Node *L)
{
struct Node *q;
q = L->Next;
while (q != NULL)
{
printf("%d ", q->Data);
q = q->Next;
}
}
void Insert(struct Node *L, int n)
{ //插入数据
struct Node *p, *q;
p = L;
q = (struct Node *)malloc(sizeof(struct Node));
while (p->Next != NULL && p->Next->Data < n)
{
p = p->Next;
}
q->Data = n;
q->Next = p->Next;
p->Next = q;
}
void length(struct Node *L) //计算单链表长度
{
struct Node *p;
p = L->Next;
int j = 0;
while (p != NULL)
{
p = p->Next;
j++;
}
L->Data = j;
printf("%d", j); //为什么在运行结果中无法显示?
printf("\n");
}
int main()
{
struct Node *L;
L = (struct Node *)malloc(sizeof(struct Node));
L->Next = NULL;
srand((int)time(NULL));
int i;
for (i = 1; i < 20; i++)
{
Insert(L, rand() % 200);
}
length(L);
Print(L);
return 0;
}
void length(Node *L) //计算单链表长度
{
Node *p;
p=L->Next;
int j=0;
while(p!=NULL)
{
p=p->Next;
j++;
}
L->Data = j;
printf("%d",j); //为什么在运行结果中无法显示?
printf("\n");
}