StefanSalewski / NimProgrammingBook

Computer Programming with the Nim Programming Language -- A gentle Introduction
262 stars 19 forks source link

The tail insert of linked object #25

Open geohuz opened 1 year ago

geohuz commented 1 year ago

In the chapter of "Reference and Pointers", I'm wondering how can I code the "tail insert" instead of the head insert of linked object? The current example insert item as reverse order.


type
  Friend = ref object
    name: string
    next: Friend  

var
  f: Friend           
  node: Friend
  n: string 

new(f)
node = f
while true:
  write(stdout, "Name of friend: ")
  n = readline(stdin)
  if n=="" or n=="quit":
    break
  node.next = Friend(name: n)
  node = node.next

while f!= nil:
  echo f.name
  f = f.next        
StefanSalewski commented 1 year ago

I am happy that people like you in China can still access my book, I heard that a lot of stuff is blocked by your leaders. And I hope the English language is not a too big problem for people in China.

For your question, inserting at both ends or the middle of a linked list is generally not that easy and fast. Typically, we store the head of the list, and so can easily replace that element by a new one. For this data structure, we would have to traverse the list to the end, to find the last element, before we can add the new one at that position. Similar for inserting somewhere in the middle. To enable adding new elements at the beginning and at the end, we may also store an additional pointer to the end, but that makes things more complicated.

For general list structures and its operations, you should be able to find a lotof information in the Internet or the local library. It is not that different for Nin than to C or other languages, but when you are using refs in Nim, you don't have to care for freeing nodes of course.