在递归的帮助下将元素插入链表



这个 Pascal 代码在 "while 循环" 的帮助下将一个新元素插入到链表中:

program linked_list;
type
pointer_typ = ^record_2;
record_2 = record
data: integer;
next: pointer_typ;
end;
procedure Push_int(var p: pointer_typ; x: integer);
var
temp: pointer_typ;
begin
new(temp);
temp^.data := x;
temp^.next := p;
p := temp
end;
var
first: pointer_typ;
x: integer;
begin
first := nil;
while not Seekeof do begin
read(x);
Push_int(first, x)
end;
end.

你能帮助制作一个在递归(而不是while循环(的帮助下向链表插入新元素的过程吗? 我尝试并得到了错误的结果(例如,下面的代码以"队列顺序"返回值,但不是我想要的"堆栈顺序"(:

program linked_list;
type
pointer_typ = ^record_2;
record_2 = record
data: integer;
next: pointer_typ;
end;
procedure Push_int(var p: pointer_typ);
var
temp: pointer_typ;
x: integer;
begin
read(x);
new(temp);
temp^.data := x;
temp^.next := p;
p := temp;
if Seekeof then
exit
else
Push_int(p^.next)
end;
var
first: pointer_typ;
begin
first := nil;
Push_int(first);
end.

谢谢。

看起来,这个工作正确:

program linked_list;
type
pointer_typ = ^record_2;
record_2 = record
data: integer;
next: pointer_typ;
end;
procedure Push_int(var p: pointer_typ; x: integer);
var
temp: pointer_typ;
begin
new(temp);
temp^.data := x;
temp^.next := p;
p := temp;
if Seekeof then
exit
else begin
read(x);
Push_int(p, x)
end;
end;
var
first: pointer_typ;
x: integer;
begin
first := nil;
read(x);
Push_int(first, x)
end.

相关内容

  • 没有找到相关文章

最新更新