通过一趟遍历确定单链表中值最大的结点
程序员文章站
2024-02-03 17:02:40
...
[程序代码]
#include<stdio.h>
#include<stdlib.h>
short InitHeadNode(struct Node* &, struct Node* &);
short Traversal(struct Node* &);
short RearInsert(struct Node* &, struct Node* &, short);
short GetListLength(struct Node* &);
/* 链表结点定义 */
struct Node
{
short data;
struct Node *next;
};
int main()
{
struct Node *head1;
struct Node *rear1;
/* 初始化头结点 */
if(InitHeadNode(head1, rear1) == -1)
{
/* 头结点申请失败, 程序直接结束 */
exit(0);
}
short temp;
/* 向链表中插入数据结点 */
while(1)
{
while(scanf("%hd", &temp) != 1)
{
while(getchar() != '\n') ;
printf("请输入合法数据.\n");
}
if(temp == -1)
{
break;
}
if(RearInsert(head1, rear1, temp) == -1)
{
/* 申请结点失败 */
exit(0);
}
}
/* 输出链表数据域中的最大值 */
if(GetListLength(head1) > 0)
{
/* 表非空 */
printf("Max : %3hd.\n", Traversal(head1));
}
/* */
return 0;
}
/* 获取表长 */
short GetListLength(struct Node* &head)
{
struct Node *p = head -> next;
short length = 0;
while(p != NULL)
{
length ++;
p = p -> next;
}
return length;
}
/* 尾插法 */
short RearInsert(struct Node* &head, struct Node* &rear, short value)
{
struct Node *p = (struct Node*)malloc(sizeof(struct Node));
if(p != NULL)
{
/* 结点申请成功 */
rear -> next = p;
p -> next = NULL;
p -> data = value;
rear = p;
return 1;
}
else
{
/* 结点申请失败 */
return -1;
}
}
/* 寻找单链表中值最大的元素结点 */
short Traversal(struct Node* &head)
{
struct Node *p = head -> next;
short Max = p != NULL ? p -> data : 0;
while(p != NULL)
{
if(p -> data > Max)
{
Max = p -> data;
}
p = p -> next;
}
return Max;
}
/* 初始化头结点 */
short InitHeadNode(struct Node* &head, struct Node* &rear)
{
struct Node *p = (struct Node*)malloc(sizeof(struct Node));
if(p != NULL)
{
/* 头结点申请成功 */
head = p;
head -> data = 0;
head -> next = NULL;
rear = head;
return 1;
}
else
{
/* 头结点申请失败 */
return -1;
}
}
[运行结果]
推荐阅读