Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

The tail insert of linked object #25

Open
geohuz opened this issue Mar 12, 2023 · 1 comment
Open

The tail insert of linked object #25

geohuz opened this issue Mar 12, 2023 · 1 comment

Comments

@geohuz
Copy link

geohuz commented Mar 12, 2023

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
Copy link
Owner

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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants