针对带表头结点的单链表,给出算法中使用的单链表的存储结构(数据类型)的定义。试编写下列函数。

2025-02-28 13:40:20
推荐回答(1个)
回答1:

// 节点数据结构定义
struct Node
{
int data;
struct Node *next;
};
// 定位第i个节点

struct Node *Locate(struct Node head, int i)
{
struct Node *p = &head;
int k;
for(k = 0; k < i && p; ++k)
{
p = p->next;
}
return p;
}
// 寻找最大值

int max(struct Node head)
{
struct Node *p = head.next;
int max = -1;
if(p != NULL)
{
// 若第一个节点不空,则先将最大值初始化成第一个节点的值,再与后面节点的值进行比较

max = p->data;
p = p->next;
while(p)
{
max = p->data > max ? p->data : max;
p = p->next;
}
}
return max;
}
// 同值节点计数

int number(struct Node head, int n)
{
struct Node *p = head.next;
int count = 0;
while(p)
{
if(p->data == n)
{
++count;
}
p = p->next;
}
return count;
}

验证的代码请自行编写。