You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Free Pascal单链表构建顺序错误:如何生成输入顺序的链表?

问题:Free Pascal单链表实现顺序错误的解决方法

我正在用Free Pascal的指针实现单链表,任务要求如下:

编写程序从标准输入流读取整数,直到遇到文件结束(EOF),随后按输入顺序将所有输入的数字打印两次。数字数量未知,禁止对数量做明确限制。

我的程序构建的链表顺序错误,请问如何构建出符合输入顺序的链表?以下是我的代码:

program InputStreamNumbers;
type
    itemptr = ^item;
    item = record
        data: Integer;
        next: itemptr;
    end;
var
    first, tmp: itemptr;
    n: Integer;
begin
    first := nil;            { make the list properly empty! }
    while not SeekEof do            { number reading loop }
    begin
        read(n);
        new(tmp);               { created }
        tmp^.data := n;         { fill out}
        tmp^.next := first;
        first := tmp;           { include in the list}
    end;

    tmp := first;           { go through the list from beginning to end }
    while tmp <> nil do             
    begin
        writeln(tmp^.data);
        tmp := tmp^.next;        { move to the next element}
    end;
end.

你的代码是把新节点插入到链表头部,导致最终链表顺序和输入顺序完全相反。要保持输入顺序,需要将新节点插入到链表尾部,这时候需要额外维护一个指向尾节点的指针,避免每次遍历找尾的低效操作。

修改后的代码:

program InputStreamNumbers;
type
    itemptr = ^item;
    item = record
        data: Integer;
        next: itemptr;
    end;
var
    first, last, tmp: itemptr;
    n: Integer;
begin
    first := nil;
    last := nil;            { 初始化头尾指针 }
    while not SeekEof do
    begin
        read(n);
        new(tmp);
        tmp^.data := n;
        tmp^.next := nil;   { 新节点作为尾部,next设为空 }
        
        if first = nil then
        begin
            first := tmp;    { 空链表时,头尾都指向新节点 }
            last := tmp;
        end
        else
        begin
            last^.next := tmp; { 将新节点接到当前链表尾部 }
            last := tmp;       { 更新尾指针到新节点 }
        end;
    end;

    { 第一次按输入顺序打印 }
    tmp := first;
    while tmp <> nil do
    begin
        writeln(tmp^.data);
        tmp := tmp^.next;
    end;

    { 第二次按输入顺序打印 }
    tmp := first;
    while tmp <> nil do
    begin
        writeln(tmp^.data);
        tmp := tmp^.next;
    end;
end.

关键改动说明:

  1. 新增last指针跟踪链表尾节点,避免每次插入都遍历找尾
  2. 新节点的next固定设为nil,保证链表尾部的正确性
  3. 分空链表和非空链表两种场景处理插入逻辑,确保链表初始状态正确
  4. 补充了第二次遍历打印,满足任务要求的"按输入顺序打印两次"

内容的提问来源于stack exchange,提问作者KukuruzoFirst

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.09 06:31:00