2013-10-19 71 views
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

那么,这里有什么问题?

回答

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;