编程知识 cdmana.com

How to solve this problem

#include<stdio.h>#include<stdlib.h>#include<limits.h>typedef struct node {	int data;	struct node*next;}Node;int main(){	int T, n, value;	scanf_s("%d", &T);	while (T--)	{		Node	*p, *q, *head = NULL, *t;		int max = INT_MIN, index = 0, num = 0;		scanf_s("%d", &n);		while (n--)		{			scanf_s("%d", &value);			index++;			if (value > max)			{				max = value;				num = index;			}			p = (Node*)malloc(sizeof(Node));			p->next = NULL;			if (head == NULL)			{				head = p;			}			else			{				q->next = p;			}			q = p;		}		printf("max=%d num=%d\n", max, num);	}	return 0;}

The program won't run , appear    C4703     Local pointer variables that may not be initialized are used “q” The problem of , The official solution is invalid .

The ultimate goal is to determine the node with the largest value in the single linked list




Take the answer :

No malloc You don't have to apply for memory space , Program plus two initialization

#include<stdio.h>#include<stdlib.h>#include<limits.h>typedef struct node {    int data;    struct node*next;}Node;int main(){    int T, n, value;    scanf_s("%d", &T);    while (T--)    {        Node    *p, *q, *head = NULL, *t;        int max = INT_MIN, index = 0, num = 0;        scanf_s("%d", &n);        while (n--)        {            scanf_s("%d", &value);            index++;            if (value > max)            {                max = value;                num = index;            }            p = (Node*)malloc(sizeof(Node));            p->next = NULL;            q = (Node*)malloc(sizeof(Node));            q->next = NULL;            if (head == NULL)            {                head = p;            }            else            {                q->next = p;            }            q = p;        }        printf("max=%d num=%d\n", max, num);    }    return 0;}

版权声明
本文为[CSDN Q & A]所创,转载请带上原文链接,感谢
https://cdmana.com/2022/134/202205072139434903.html

Scroll to Top