简体   繁体   English

以升序创建列表

[英]Create a list in ascending order

I want to create a list in ascending order: 我想按升序创建一个列表:

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.

So, when I run the program, the inserted numbers are: 因此,当我运行该程序时,插入的数字为:

1 - 5 - 58 - 95 - 3 - 0 1-5-58-95-3-0

The expected result is: 预期结果是:

0 - 1 - 3 - 5 - 58 - 95 0-1-3-5-58-95

But, when the programs writes the list: 但是,当程序编写列表时:

1 - 0 - 5 - 3 - 58 - 95 1-0-5-3-58-95

So, what's the problem here? 那么,这是什么问题呢?

Basically it's because your program can't insert a node before the list you build, because your "Cursor" variable, after which you insert elements, starts with the first element. 基本上是因为您的程序无法在生成的列表之前插入节点,因为在插入元素之后的“ Cursor”变量从第一个元素开始。

My suggested improvement of procedure "insertarOrdenado" is: 我建议对程序“ 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;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM