Prolog Tutorial
Selected Reading
- Prolog - Discussion
- Prolog - Useful Resources
- Prolog - Quick Guide
- Monkey and Banana Problem
- Prolog - Linked Lists
- Towers of Hanoi Problem
- Prolog - Examples of Cuts
- Prolog - Basic Programs
- Tree Data Structure (Case Study)
- Prolog - Built-In Predicates
- Prolog - Inputs and Outputs
- Prolog - Different and Not
- Prolog - Backtracking
- Recursion and Structures
- Prolog - Lists
- Conjunctions & Disjunctions
- Loop & Decision Making
- Prolog - Operators
- Prolog - Data Objects
- Prolog - Relations
- Prolog - Basics
- Prolog - Hello World
- Prolog - Environment Setup
- Prolog - Introduction
- Prolog - Home
Selected Reading
- Who is Who
- Computer Glossary
- HR Interview Questions
- Effective Resume Writing
- Questions and Answers
- UPSC IAS Exams Notes
Prolog - Linked Lists
Prolog - Linked Lists
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](/prolog/images/pnked_psts.jpg)
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