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

C语言,编写程序。已知head指向一个带头结点的单向链表,链表中每个结点包含数据域(date)和指针域(next),
数据类型为整形。请分别编写函数,在链表中查找数据域值最大值的结点。
(1)由函数值返回找到最大值。
(2)由函数值返回最大值所在结点的地址值。

#include<stdio.h>
#include<stdlib.h>
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;
}

追问

运行不出来呀

追答

用的vc6.0编译器?将结构体定义里面_Node *next改为struct _Node *next

温馨提示:答案为网友推荐,仅供参考
相似回答