递归求单链表最大值

需要注意递归的形式,不要忘了在最后返回!
注意链表创建的方法,本次使用头插法!
多种尝试,注释部分标注正确的即可正确运行
 

#include <stdio.h>
#include <stdlib.h>
typedef struct LNode
{
int data;
struct LNode *next;
}LNode;

//LNode *createList( int a[], int n)
//{
// LNode *p = (LNode*) malloc(sizeof (LNode));
// p->next=NULL;
// LNode *s;
// int i=0;
// while (i<n)
// {
// s=(LNode*) malloc(sizeof (LNode));
// s->next=NULL;
// s->data=a[i++];
// s->next=p->next;
// p->next=s;
// }
// return p;
//}
LNode *createList(int a[], int n) {
LNode *head = (LNode*)malloc(sizeof(LNode));
head->next = NULL;
LNode *p = head; // Use a separate pointer to keep track of the last node.

for (int i = 0; i < n; i++) {
LNode *s = (LNode*)malloc(sizeof(LNode));
s->next = NULL;
s->data = a[i];
p->next = s;
p = s; // Update the last node to the newly created node.
}

return head->next; // Return the first node (not the dummy head).
}

LNode *findmax(LNode *p)
{
if(p->next->next==NULL)
return p->data > p->next->data ? p:p->next;
return findmax(p->next);
}
//LNode *findmax(LNode *p) {//正确1
// if (p == NULL) {
// return NULL;
// }
//
// LNode *maxNode = p; // Assume the first node as the maximum
//
// while (p != NULL) {
// if (p->data > maxNode->data) {
// maxNode = p; // Update maxNode if a larger value is found
// }
// p = p->next;
// }
//
// return maxNode;
//}
//LNode *findmax(LNode *p) {//正确2
// if (p == NULL) {
// return NULL;
// }
//
// LNode *maxNode = p; // Assume the first node as the maximum
//
// LNode *nextMax = findmax(p->next);
//
// if (nextMax != NULL && nextMax->data > maxNode->data) {
// maxNode = nextMax;
// }
//
// return maxNode;
//}
int main(){
int a[7]={17,2,5,9,6,90,9};
LNode *p, *q;
p=createList(a,7);
q= findmax(p);

printf("最大值为:%d", q->data);
return 0;
}
posted @ 2023-10-16 22:22  池恩卓  阅读(178)  评论(0)    收藏  举报