回 帖 发 新 帖 刷新版面

主题:建立一个有序链表  的问题?

program aa;
type
  point=^node;
  node=record
         data:integer;
         link:point;
       end;
var
  head,last,next:point;
  x:integer;
procedure insert(x:integer; var head:point);   {插入节点过程}
  var
    q,last,next:point;
  begin
    new(q);
    new(last);
    q^.data:=x;
    if x<=head^.data then begin             {如果x比第一个节点值小,插在最前面}
                            q^.link:=head;
                            head:=q;
                          end
                     else begin             {找到合适的位置并插入}
                            next:=head;
                            while (x>=next^.data) and (next<>nil) do {找位置过程}
                              begin
                                last^.link:=next;
                                next:=next^.link;
                              end;
                            if x<=next^.data then            {插入}
                                               begin
                                                 last^.link:=q;
                                                 q^.link:=next;
                                               end
                                             else          {插入到链表尾部}
                                               begin
                                                 next^.link:=q;
                                                 q^.link:=nil;

                                               end

                          end;

  end;

begin                {main}
  read(x);           {建立第一个节点}
  new(head);
  head^.data:=x;
  head^.link:=nil;
  read(x);           {开始插入数值}
  while x>=0 do
    begin
      insert(x,head);
      read(x);
    end;

  writeln;            {输出链表内容}
  next:=head;
  while next<>nil do
    begin
      write(next^.data:5);
      next:=next^.link;
    end;
end.



此程序在执行过程中出216号错误,请高手帮忙调试一下,看看错在什么位置。
我调试的时候主程序没发现错误。
附件里是源程序,下载后可以直接运行的。

回复列表 (共1个回复)

沙发

指针我不怎么熟悉,所以可能改动大了一点:

program aa;
type
  point=^node;
  node=record
         data:integer;
         link:point;
       end;
var
  head,last,next:point;
  x:integer;
procedure insert(x:integer; var head:point);   {插入节点过程}
  var
    q,next:point;
begin
  new(q);
  q^.data:=x;
  if x<=head^.data then begin             {如果x比第一个节点值小,插在最前面}
    q^.link:=head;
    head:=q;
  end else begin             {找到合适的位置并插入}
    next:=head;
    while (x>=next^.link^.data) or (next^.link<>nil) do begin{找位置过程}
      next:=next^.link;
    end;
    q^.link:=next^.link;
    next^.link:=q;
  end;
end;

begin                {main}
  read(x);           {建立第一个节点}
  new(head);
  head^.data:=x;
  head^.link:=nil;
  read(x);           {开始插入数值}
  while x>=0 do begin
    insert(x,head);
    read(x);
  end;
  writeln;            {输出链表内容}
  next:=head;
  while next<>nil do
    begin
      write(next^.data:5);
      next:=next^.link;
    end;
end.

我来回复

您尚未登录,请登录后再回复。点此登录或注册