Stacks on Pascal

I solve a problem about the towers of Hanoi, if in general. I wrote procedures for working with PUSH, POP,and SHOW stacks. At first, they were written for a single stack, then changed so that you can work with three stacks (arrays in fact). After the conversion, there was a problem with the PUSH procedure: it gets the name of the stack (array) and the element to put in it, but it does not put it in the right place. I roughly understand what the problem is, but I don't know how to solve it. And with the POP procedure, I think the same problem will occur.. Help, who is not difficult

var


n,t:integer;
 type ta=array[1..10] of integer; 
 var
 a:ta;
 S1,S2,S3:ta;
 procedure PUSH (a:ta;c:integer);
 begin
 if n<10 then begin {до 10 элементов}
 n:=n+1; {Добавляю элемент}
  a[n]:=с; {и значение}
  end
  else
  writeln ('Переполнение');
 end;
 {функция удаления элемента из стека}
  procedure POP(a:ta);
 begin
  a[n]:=t;
  n:=n-1; {Убираю элемент}
 end;
 {процедура вывода элементов стека на экран}
procedure SHOW; 
 begin
   var i:integer;
   writeln ('S1:');
   for i:=10 downto 1 do
   writeln (S1[i],' ');

   writeln ('S2:');
   for i:=10 downto 1 do
   writeln (S2[i],' ');

   writeln ('S3:');
   for i:=10 downto 1 do
   writeln (S3[i],' ');
   end;
{Основная программа}
begin
 n:=0;
 var i:integer;
 for i:=1 to 10 do 
 begin
  PUSH(S1,(11-i));
 end;
 n:=0;
 for i:=1 to 10 do 
  PUSH(S2,0);
  n:=0;
 for i:=1 to 10 do 
  PUSH(S3,0);

 SHOW;
 end.
Author: victoriyap, 2017-10-14

2 answers

You have the stack element count variables (n) common to all stack variables.

I don't know much about Pascal and the implementation you use, but I would venture to assume that you can create structures (in Pascal, this is called record). Make one of these from the stack as an array and the number of elements in it, declare it as a type, and use it in your procedures. Something like:

stek = record
  a: ta; // массив
  count: integer; //число элементов в нем, вместо n
end;

If your Pascal is object-oriented (Delphi, Lazarus, Fripascal, etc.), then instead of structures create a class.

 3
Author: Trashbox Bobylev, 2017-10-15 05:41:29

Parameters of procedures and functions that you modify internally must be declared as mutable-with the keyword var. For example:

procedure PUSH (var a: ta; c: integer);
..
procedure POP (var a: ta);

Otherwise, you change the local (for the function) copy of the array and when you exit it, all changes are lost.

 1
Author: Alekcvp, 2017-10-15 05:40:23