Q:

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.

A:

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. We don't know what the max Node is until we've looped through all the nodes.

