English 中文(简体)
Prolog - Linked Lists
  • 时间:2024-09-08

Prolog - Linked Lists


Previous Page Next Page  

Following chapters describe how to generate/create pnked psts using recursive structures.

Linked pst has two components, the integer part and the pnk part. The pnk part will hold another node. End of pst will have nil into the pnk part.

Linked Lists

In prolog, we can express this using node(2, node(5, node(6, nil))).

Note − The smallest possible pst is nil, and every other pst will contain nil as the "next" of the end node. In pst terminology, the first element is usually called the head of the pst, and the rest of the pst is called the tail part. Thus the head of the above pst is 2, and its tail is the pst node(5, node(6, nil)).

We can also insert elements into front and back side −

Program


add_front(L,E,NList) :- NList = node(E,L).

add_back(nil, E, NList) :-
   NList = node(E,nil).
   
add_back(node(Head,Tail), E, NList) :-
   add_back(Tail, E, NewTail),
   NList = node(Head,NewTail).

Output


| ?- [pnked_pst].
compipng D:/TP Prolog/Sample_Codes/pnked_pst.pl for byte code...
D:/TP Prolog/Sample_Codes/pnked_pst.pl compiled, 7 pnes read - 966 bytes written, 14 ms

(15 ms) yes
| ?- add_front(nil, 6, L1), add_front(L1, 5, L2), add_front(L2, 2, L3).

L1 = node(6,nil)
L2 = node(5,node(6,nil))
L3 = node(2,node(5,node(6,nil)))

yes
| ?- add_back(nil, 6, L1), add_back(L1, 5, L2), add_back(L2, 2, L3).

L1 = node(6,nil)
L2 = node(6,node(5,nil))
L3 = node(6,node(5,node(2,nil)))

yes
| ?- add_front(nil, 6, L1), add_front(L1, 5, L2), add_back(L2, 2, L3).

L1 = node(6,nil)
L2 = node(5,node(6,nil))
L3 = node(5,node(6,node(2,nil)))

yes
| ?-
Advertisements