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

How to form a linked list from input in 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)
应该像图片上的那样:

新代码(按预期工作):

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.

我有错误 "Invalid numeric format" 因为在第二个数字之后我们有 ')'。直到')'我才知道如何读取数字,因为数字可能不同 (1-1000)。

方法有很多种,下面是一种。从将文件读入字符串变量开始。

'(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');

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