简体   繁体   English

使用数组的堆栈实现

[英]stack implementation using arrays

I am implementing a stack using arrays here is the programme i have written 我正在使用数组实现堆栈,这是我编写的程序

#include<stdio.h>

int path[100];  //stores the path vertices
int tp=-1;      //tp is top pointer in stack
//int graph_matrix[100][100];   
//int child_matrix[100][100];

void push(int vi)
{
  int i=0;
  tp++;
  path[tp]=vi;
  printf("pushing %d in index %d value: %d \n",vi,tp,path[tp]);
  for(i=0;i<5;i++)
    printf("%d  ",path[i]);
}

void pop()
{
  printf("popping %d\n",path[tp]);
  if(tp==-1) {
    printf("stack empty\n");
    goto end2;
  }

  path[tp]=-1;
  tp--;

end2:
  printf("");
}


int eg()
{
  int i=0;
  for(i=0;i<100;i++) 
    path[i]=-1;     //initializing path array tp -1

  print_path();
  push(30);
  print_path();
  push(40);
  print_path();
  push(50);
  print_path();
  //pop();
  print_path();
  push(60);
  print_path();
}

void print_path()
{
  int j=0;

  for(j=0;j<10;j++)
  {
    printf("%d    ",path[j]);
    j++;
  }
  printf("\n");
}

int main()
{
  eg();
  return 0;
}

But THe output shows me something else: 但是输出显示了其他内容:

Output: 输出:

-1 -1 -1 -1 -1 -1 -1 -1 -1 -1

pushing 30 in index 0 value: 30 将30推入索引0值:30

30 -1 -1 -1 -1 30 -1 -1 -1 -1 30 -1 -1 -1 -1 30 -1 -1 -1 -1

pushing 40 in index 1 value: 40 将40推入索引1的值:40

30 40 -1 -1 -1 30 -1 -1 -1 -1 30 40 -1 -1 -1 30 -1 -1 -1 -1

pushing 50 in index 2 value: 50 在索引2值中推送50:50

30 40 50 -1 -1 30 50 -1 -1 -1 30 40 50 -1 -1 30 50 -1 -1 -1

30 50 -1 -1 -1 30 50 -1 -1 -1

pushing 60 in index 3 value: 60 在索引3值中推入60:60

30 40 50 60 -1 30 50 -1 -1 -1 30 40 50 60 -1 30 50 -1 -1 -1

Can anyone please explain the output? 谁能解释一下输出结果吗?

As mentioned in the comments, you increment the loop variable twice. 如注释中所述,将循环变量增加两次。

Why not simply print the stack in its entirety instead of only 5 elements? 为什么不简单地打印整个堆栈而不是仅打印5个元素?

void print_path(void)
{
  int j;

  for(j = 0; j <= tp; j++)
  {
    printf("%d ", path[j]);
  }
  printf("\n");
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM