如何从Pascal中的输入形成链表?

时间:2017-11-23 08:38:30

标签: list pascal turbo-pascal

我有一个输入文件格式:

(a n),(a n-1),...(a 0)

如何在Pascal

中形成如下所示的列表
type
  tt = ^t;
  t = record
       a: Integer;
       n: Integer;
       next: tt
  end;

例如:
(5 10),(5 9),(5 8),(5 7),(5 6),(5 5),(5 4),(5 3),(5 2),(5 1), (5 0)
应该像图像上一样:
enter image description here

新代码(按预期工作):

program ex4_19;

type
  tt = ^t;
  t = record
       a: Integer;
       n: Integer;
       next: tt
  end;

var
  ukzv, ukrs: tt;
  inp: text;
  raDone: boolean;
  i: integer;
  str: string;
begin
  assign(inp, 'f1.txt'); reset(inp);
  assign(output, 'out.txt'); rewrite(output);

  new(ukzv);
  ukrs:=ukzv; 

  read(inp, str);
  writeln(str);

  for i:=1 to length(str) do
  begin
    case str[i] of
      '(':
      begin
         raDone:=false;
         new(ukzv^.next);
         ukzv:=ukzv^.next;
         ukzv^.a:=0;
         ukzv^.n:=0;
      end;
      '0' .. '9':
      begin
         if raDone = false then
            ukzv^.a:=ukzv^.a * 10 + (ord(str[i]) - ord('0'))
         else
            ukzv^.n:=ukzv^.n * 10 + (ord(str[i]) - ord('0'));
      end;
      ' ':
      begin
         if raDone = false then
         begin
            raDone:=true;
         end;
      end;
      ')':
      begin
         ukzv^.next:=nil;
      end;
    end;
  end;

   ukzv:=ukrs;

   while ukzv^.next <> nil do
   begin
     writeln(ukzv^.next^.a, ' ', ukzv^.next^.n);
     ukzv:=ukzv^.next;
   end;
end.

我有错误&#34;数字格式无效&#34;因为在第二个数字后我们有&#39;。我不知道如何读取数字直到&#39;)&#39;因为数字可能不同(1-1000)。

1 个答案:

答案 0 :(得分:1)

有不同的方式,一种是以下方式。首先将文件读入字符串变量。

'(5 10), (5 9), (5 8), (5 7), (5 6), (5 5), (5 4), (5 3), (5 2), (5 1), (5 0)'

然后使用循环(for..dorepeat..untilwhile..do)逐个浏览字符。使用案例陈述来决定行动。

此处列出的每个字符的处理应该直接实现为case语句。

您需要一个布尔值(例如raDone: boolean)来指示新数字是否会转到记录中的an

Get next char, '(', you know it's time to link in a new record (`r` in the following).
Get next char, '5', it's a digit and `not raDone`, so you accumulate `r.a` with it. See below!
Get next char, ' ', it's a space and `not raDone`, you know that entry for `r.a` has ended, set `raDone` to indicate next digits belong to `r.n`.
Get next char, '1', it's a digit and `raDone`, so you accumulate `r.n` with it.
Get next char, '0', it's a digit and `raDone`, so you accumulate `r.n` with it.
Get next char, ')', you know the entry for the current record is ready. 
Get next char, comma, nothing to do, just skip it
Get next char, ' ', space, nothing to do, just skip it

使用十进制数字(从字符转换)累加二进制值(例如r.n):

r.n := r.n * 10 + (ord(decimal character) - ord('0');

您可能希望为输入字符串中的错误内容添加错误检查。

相关问题