简体   繁体   English

如何返回指向链表中最大值的指针?

[英]How can return a pointer pointing to the largest value in a linked list?

This is my attempt 这是我的尝试

// Return a pointer to node with the largest value.
// You may assume list has at least one element

Node * pointerToMax(LinkedList *list) {

  assert(list!=NULL);
  assert(list->head != NULL);

  Node *p, *q;
  p = list->head;
  q = list->head;
  int max = q->data;

  while(p != NULL){
    if(p->data > max){
      max = p->data;
    }
    return p;
    p = p->next;
  }
}

Here are the struct definitions. 这是结构定义。

struct Node {
  int data;
  Node *next;
};

struct LinkedList {
  Node *head;
  Node *tail;
};

I'm trying to figure out how to return a pointer that points to the largest value, but I can't exactly figure out how to return the pointer to variable max , and I'm not even sure if the max variable is being updated correctly. 我试图弄清楚如何返回一个指向最大值的指针,但是我不能确切地弄清楚如何将指针返回给变量max ,我甚至不确定max变量是否正在更新。正确地。

You want something like this: 您想要这样的东西:

Node *maxNode = p;
int max = p->data;
while(p != NULL){
  if(p->data > max){
    max = p->data;
    maxNode = p;
  }
  p = p->next;
}
return maxNode;

There is no reason to return in your while loop. 没有理由在while循环中return We don't know what the max Node is until we've looped through all the nodes. 我们不知道是什么最大Node是,直到我们完成了所有的节点循环。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 返回链表中的最大值 - Returning largest value in linked list 如何创建包含字符串作为键值并指向链表的无序映射? - How can I create an unordered map containing a string as key value and pointing to a linked list? 复制一个列表并返回指向第二个列表的指针 - copy a list and return the pointer, pointing to the second list 从单链接列表的头部删除节点之后,指向无用值的头部指针 - Head pointer pointing to garbage value after deleting node from head in singly linked list 如何返回列表中指针的值? - How to return the value of a pointer in a list? 如何使用它指向的指针将指针传递给指向 function 的指针? - How can I pass a pointer to pointer to a function using the pointer it is pointing to? 如何创建一个链接列表,其中一个节点指向多个其他注释? - How can I create a linked list where one node is pointing to more than one other note? 如何在给定头节点的情况下递归地找到链表中的最大项? - How can I find the largest item in a linked list recursively given the head node? 如何找到指向链接列表中特定节点的指针数量? - How to find how many pointers are pointing to a particular node in a linked list? 如何通过 return 语句更改指针指向的位置? - How do I change where the pointer is pointing to through a return statement?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM