好吧,对于业余程序员来说,这个问题可能听起来很愚蠢。但严重的是,这让我感到困扰,欢迎对我的这个疑问做出严肃的回答。我刚刚开始学习我的第一门数据结构课程。而困扰我的是:
假设使用 C,
//Implementing a node
struct Node
{
int data;
struct *Node;
};
Run Code Online (Sandbox Code Playgroud)
现在,在创建节点时,为什么我们在使用 malloc() 的地方使用动态内存分配技术。我们不能只创建一个“结构节点”类型的变量。即类似:
struct Node N1;
//First node - actually second where !st Node is assumed to be Head.
struct Node *Head = &N1;
struct Node N2;
N2.(*Node) = &N1;
Run Code Online (Sandbox Code Playgroud)
好吧,我的代码的某些部分可能不正确,因为我只是一个初学者并且不精通 C。但是知道您可能已经理解我的基本意思。为什么我们不创建 Node 类型的 Node 类型的变量来分配内存 t 新节点为什么要进入动态内存分配的复杂性?
当我memset在printNGE函数内部使用时,我也得到了正确的结果,当我将数组元素初始化为-1时main(),我得到了正确的结果.
但是当我printNGE使用for循环在函数中初始化相同时,我得到了错误的答案.由于某种原因,似乎数组元素的初始值在while循环的else部分内没有改变?请告诉我这种差异可能是什么原因.
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<stack>
using namespace std;
/* arr[] of size n */
void printNGE(int arr[], int n)
{
int i = 0;
stack <int> s;
int ans[n];
for(i=0;i<n;i++)//Set all the elements to -1
ans[i] = -1;
//memset(ans,-1,sizeof(ans));
while (i<n)
{
if(s.empty() || arr[s.top()]>arr[i])
s.push(i++);
else
{
ans[s.top()]=arr[i];
s.pop(); //pop till incoming element is greater
}
}
for(i=0;i<n;i++)
printf("%d -> %d\n",arr[i],ans[i]);
}
int main()
{
int arr[]= {11, 13, 21, …Run Code Online (Sandbox Code Playgroud)