0

昇順でリストを作成したい:

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

それで、ここで何が問題なのですか?

4

1 に答える 1

3

基本的には、作成するリストの前にプログラムがノードを挿入できないためです。これは、要素を挿入した後の「カーソル」変数が最初の要素から始まるためです。

手順「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;
于 2013-10-27T10:39:46.650 に答える