求带头结点的单链表最大值
时间: 2024-06-12 21:04:39 浏览: 3
假设单链表的头结点为head,那么可以使用一个变量max来记录当前的最大值,然后遍历链表,依次比较每个节点的值和max的大小,如果节点的值比max大,则更新max的值。最后遍历完成后,max就是链表中的最大值。
代码示例:
```
// 带头结点的单链表结构体
struct ListNode {
int val;
ListNode *next;
ListNode(int x) : val(x), next(NULL) {}
};
int getMax(ListNode* head) {
if (head == NULL || head->next == NULL) {
return INT_MIN; // 如果链表为空或只有一个节点,则返回最小值
}
int maxVal = head->next->val; // 初始化最大值为第一个节点的值
ListNode* cur = head->next->next; // 从第二个节点开始遍历
while (cur != NULL) {
if (cur->val > maxVal) {
maxVal = cur->val; // 更新最大值
}
cur = cur->next;
}
return maxVal;
}
```
注意:在计算最大值时,需要先判断链表是否为空或只有一个节点,如果是,则返回INT_MIN或该节点的值。
相关问题
求出不带头结点的单链表中的最大值并返回
好的,这个问题很简单,可以通过遍历链表,比较每个节点的值来得出最大值,下面是代码示例:
```
int getMax(Node* head) {
if (head == NULL) {
return -1; // 空链表返回-1
}
int max_val = head->val;
Node* p = head->next;
while (p != NULL) {
if (p->val > max_val) {
max_val = p->val;
}
p = p->next;
}
return max_val;
}
```
当然,这里假设单链表中元素都是正整数。如果有负数,可以将 `max_val` 初值设为链表第一个节点的值,而不是0。
试写在一算法在带头结点的单链表结构上求最大结点值
算法如下:
1. 初始化变量max_value为链表头结点的值。
2. 遍历链表的每个结点,从头结点的下一个结点开始:
- 如果当前结点的值大于max_value,则将max_value更新为当前结点的值。
3. 返回max_value作为最大结点值。
代码示例(使用Python语言):
```python
def find_max_node(head):
if head is None or head.next is None:
return None
max_value = head.next.data
current = head.next
while current is not None:
if current.data > max_value:
max_value = current.data
current = current.next
return max_value
```
相关推荐
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![doc](https://img-home.csdnimg.cn/images/20210720083327.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)