【问题标题】:Create a list in ascending order按升序创建列表
【发布时间】:2013-10-19 22:31:36
【问题描述】:

我想按升序创建一个列表:

program ejListas;

type 
    tLista = ^lista
  ; lista = record
       valor : Integer
     ; sgte : tLista
    end
  ;

procedure insertarOrdenado ( var lista: tLista; dato: Integer );
    var cursor
      , listaAux
          :tLista
      ;
    begin
        if ( lista <> nil ) then
            begin
                new ( listaAux );
                listaAux^.valor := dato;

                cursor := lista;
                while ( cursor^.sgte <> nil ) and ( cursor^.valor < dato ) do 
                    cursor := cursor^.sgte;

                listaAux^.sgte := cursor^.sgte;
                cursor^.sgte := listaAux;
            end
        else
            begin
                new ( lista );
                lista^.valor := dato;
                lista^.sgte := nil;
            end;
    end;

procedure imprimirLista ( lista: tLista );
    var cursor
          :tLista
      ;
    begin
        cursor := lista;
        while ( cursor <> nil ) do
            begin
                writeln ( cursor^.valor );
                cursor := cursor^.sgte;     
            end;    
    end;

var vLista :tLista;
    dato:Integer;

begin
    read ( dato );
    while ( dato <> -1 ) do
        begin
            insertarOrdenado ( vLista, dato );
            read ( dato );
        end;
    imprimirLista ( vLista );
end.

所以,当我运行程序时,插入的数字是:

1 - 5 - 58 - 95 - 3 - 0

预期结果是:

0 - 1 - 3 - 5 - 58 - 95

但是,当程序写入列表时:

1 - 0 - 5 - 3 - 58 - 95

那么,这里有什么问题?

【问题讨论】:

    标签: list sorting pascal


    【解决方案1】:

    基本上这是因为您的程序无法在您构建的列表之前插入节点,因为您的“Cursor”变量在您插入元素之后从第一个元素开始。

    我对“insertarOrdenado”程序的建议改进是:

    procedure insertarOrdenado ( var lista: Tlista; dato: Integer );
    var cursor, listaAux:Tlista;
    begin
        if ( lista <> nil ) then
        begin
            new ( listaAux );
            listaAux^.valor := dato;
    
            cursor := lista;
            while ( cursor^.sgte <> nil ) and ( cursor^.sgte^.valor < dato ) do
                cursor := cursor^.sgte;
    
            if (cursor^.valor > dato) then
            begin
                listaAux^.sgte := cursor;
                lista := listaAux;
            end
            else
            begin
                listaAux^.sgte := cursor^.sgte;
                cursor^.sgte := listaAux;
            end;
        end
        else
        begin
            new ( lista );
            lista^.valor := dato;
            lista^.sgte := nil;
        end;
    end;
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-12-21
      • 2013-10-31
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-08-11
      相关资源
      最近更新 更多