next up previous
Up: APS105F Friday Quiz 2 Previous: B Listing for spread.t

C Listing for linkeda.t

 

type cell:
  record
    Left : pointer to cell
    Right : pointer to cell
    Column : int
    Value : real
    HasValue : boolean
  end record

procedure DeleteCell(var RowPtr : pointer to cell, ColNum : int)
  % Your code here
  %   RowPtr is the pointer to the head (left end) of the list.
  %   ColNum is the number of the column to be deleted.
  % Print an error message for non-existent cells.
end DeleteCell
        
function GetCell() : pointer to cell

    var Col : int
    var Val : string
    var Cptr : pointer to cell

    put "Column? "..
    get Col
    if Col < 0 then
        result nil
    end if

    new Cptr
    Cptr->Column := Col

    put "Value? (y/n) "..
    get Val
    if Val = "y" then
        put "Enter value " ..
        get Cptr->Value
        Cptr->HasValue := true
    else
        Cptr->HasValue := false
    end if

    result Cptr
end GetCell

procedure GetRow(var RowPtr : pointer to cell)
    % Assume that cells are input in sequence and we just have to
    % add at the end of the row

    var Cptr : pointer to cell
    var Tptr : pointer to cell    % tail pointer

    put "Enter a bunch of cells, exit with a Column Number < 1"

    RowPtr := GetCell()
    RowPtr->Left := nil
    RowPtr->Right := nil
    Tptr := RowPtr

    loop
        Cptr := GetCell()
        exit when Cptr = nil
        Tptr->Right := Cptr
        Cptr->Left := Tptr
        Cptr->Right := nil
        Tptr := Cptr
    end loop
end GetRow    

procedure PrintRow(RowPtr : pointer to cell)
    % Print front to back to front to check pointer connections

    var Cptr : pointer to cell
    
    Cptr := RowPtr

    if Cptr = nil then
        return
    end if

    put ""
    put ""

    loop    % go forward
        put "[(",Cptr->Column,") "..
        if Cptr->HasValue then
            put Cptr->Value..
        else
            put "No Value"..
        end if

        if Cptr->Right = nil then
            exit
        else
            Cptr := Cptr->Right
            put "] --> "..
        end if
    end loop

    put "]"
    put ""

    loop    % go backward
        put "[(",Cptr->Column,") "..
        if Cptr->HasValue then
            put Cptr->Value..
        else
            put "No Value"..
        end if

        if Cptr->Left = nil then
            exit
        else
            Cptr := Cptr->Left
            put "] --> "..
        end if
    end loop

    put "]"
    put ""

end PrintRow

% Main routine

var RowPtr : pointer to cell
var ColNum : int
var Ans : string

% Initialize the row first

GetRow(RowPtr)
PrintRow(RowPtr)

loop    % command loop
    put "Delete a cell? (y/n) "..
    get Ans
    exit when Ans not= "y"

    put "Column? "..
    get ColNum
    DeleteCell(RowPtr,ColNum)
    PrintRow(RowPtr)
end loop

A solution


Paul Chow
Sun Nov 24 16:01:05 EST 1996