C语言,编写程序。已知head指向一个带头结点的单向链表,链表中每个结点包含数据域(date)和指

2024-11-23 02:32:30
推荐回答(2个)
回答1:

#include

#include

typedef struct _Node
{
int data;
_Node *next;
}Node,*List;
int getMax_Value(List head)
{
if (head->next == NULL)
{
printf("链表中没有节点.\n");
exit(-1);
}
Node *ptr = head->next;
int max = ptr->data;
while (ptr->next != NULL)
{
ptr = ptr->next;
if (ptr->data > max)
{
max = ptr->data;
}
}
return max;
}
Node* getMax_Address(List head)
{
if (head->next == NULL)
{
printf("链表中没有节点.\n");
exit(-1);
}
Node *ptr = head->next;
Node *max_address = ptr;
while (ptr->next != NULL)
{
ptr = ptr->next;
if (ptr->data > max_address->data)
{
max_address = ptr;
}
}
return max_address;
}
List creatList(int num)//num为创建节点个数
{
List head = (Node*)malloc(sizeof(Node));
head->data = 0;
head->next = NULL;
Node *ptr = head;
Node *node = NULL;
int data;
while (num)
{
printf("请输入节点则值:");
scanf("%d", &data);
node = (Node*)malloc(sizeof(Node));
node->data = data;
node->next = NULL;
ptr->next = node;
ptr = node;
head->data++;
num--;
}
return head;
}
void freeList(List head)
{
Node* ptr = head;
while (head)
{
head = ptr->next;
free(ptr);
ptr = head;
}
}
int main()
{
List head=creatList(5);
printf("链表的最大值为:%d\n", getMax_Value(head));
printf("链表最大值的地址为:0x%x,%d\n", getMax_Address(head), (getMax_Address(head))->data);
freeList(head);
return 0;
}

回答2:

你好!!!
修改如下:
#include
"stdafx.h"
#include

#include

#include

#include

struct
node
{
int
data;
struct
node
*next;
};
void
main()
{
struct
node
*head,*tail,*p;
int
x;
head=tail=null;
printf("\
请输入一个整数");
scanf("%d",&x);
while(
x
!=
0
)
{
p=(struct
node
*)malloc(sizeof(struct
node));
p->data=x;
p->next=null;
if
(head
==
null)
head
=
tail
=p
;
else
tail
->next=p;
tail
=p;
printf("请输入一个整数:");
scanf("%d",&x);
}
//return(head);主函数怎么会有返回值呢,有的话也是return
0
}
我只是修改错误,至于出现的目的我不是很清楚。
要是有我们疑惑我们在交流!!