C 程序在实现链表时查找堆栈中最大的元素,但未访问数据
正在尝试查找堆栈中最大的编号。 第20行,32 top_ref->数据未被访问时出现问题 top_ref是链接列表的最后一个节点 链表和数据结构的新特性 我得到的结果是 空行 最大的数字是0C 程序在实现链表时查找堆栈中最大的元素,但未访问数据,c,malloc,C,Malloc,正在尝试查找堆栈中最大的编号。 第20行,32 top_ref->数据未被访问时出现问题 top_ref是链接列表的最后一个节点 链表和数据结构的新特性 我得到的结果是 空行 最大的数字是0 这里的要点是堆栈是指向另一个指针的指针,所以在push函数中应该被视为双指针 #include<stdio.h> #include<stdlib.h> //structure// struct node { int data; struct node *link; }
这里的要点是堆栈是指向另一个指针的指针,所以在push函数中应该被视为双指针
#include<stdio.h>
#include<stdlib.h>
//structure//
struct node
{
int data;
struct node *link;
};
//function to push elements into stack//
void push(struct node *top_ref,int x)
{
struct node *new=(struct node *)malloc(sizeof(struct node));
new->data=x;
new->link=top_ref;
top_ref=new;
}
//function to get largest element//
int largest(struct node *top_ref)
{
int temp=0;
while(top_ref!=NULL)
{
if(temp<top_ref->data)
{
temp=top_ref->data;
}
top_ref=top_ref->link;
}
return temp;
}
//function to print the stack//
void print(struct node *top_ref)
{
while(top_ref!=NULL)
{
printf("%d->",top_ref->data);
top_ref=top_ref->link;
}
printf("\n");
}
//main function//
int main()
{
struct node *stack=(struct node *)malloc(sizeof(struct node));
stack=NULL;
push(stack,1);
push(stack,5);
push(stack,6);
push(stack,3);
print(stack);
printf("the largest no. is %d\n",largest(stack));
}
top_ref=新的;无法更改原件。因为top_ref是copy。使用结构节点**top\u ref*top_ref=新;,,推叠,1;随时待命。@BLUEPIXY感谢您帮助它工作!!1这意味着该实体被处理为主堆栈,而不是副本。
#include<stdio.h>
#include<stdlib.h>
//structure//
struct node
{
int data;
struct node *link;
};
//function to push elements into stack//
void push(struct node **top_ref,int x)
{
struct node * tmp=(struct node *)malloc(sizeof(struct node));
tmp->data=x;
tmp->link=NULL;
if(top_ref==NULL){
*top_ref=tmp;
}
else{
tmp->link= *top_ref;
*top_ref=tmp;
}
}
//function to get largest element//
int largest(struct node *top_ref)
{
int temp=0;
while(top_ref!=NULL)
{
if(temp<top_ref->data)
{
temp=top_ref->data;
}
top_ref=top_ref->link;
}
return temp;
}
//function to print the stack//
void print(struct node *top_ref)
{
while(top_ref!=NULL)
{
printf("%d->",top_ref->data);
top_ref=top_ref->link;
}
printf("\n");
}
//main function//
int main()
{
struct node *stack;
stack=NULL;
//stack=NULL;
push(&stack,1);
push(&stack,5);
push(&stack,6);
push(&stack,3);
print(stack);
printf("the largest no. is %d\n",largest(stack));
}