Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to insert a new node to a single-linked list, where we do not have a pointer pointed to its head?

Given a pointer that points to an intermediate node (non-head, non-tail) on a single-link list . How to insert a new node just before the node pointed to by the given pointer ?

Example, Given single-linked list:

  A -> B -> C -> D -> E 

Given a pointer pointed to C (ptr = &C), and a new node F, how to get

 A -> B -> F -> C -> D -> E 

Attention: we do not have pointers pointed to A.

Thanks

like image 401
user1002288 Avatar asked Dec 03 '22 00:12

user1002288


2 Answers

You should be able to implement this by inserting a new C node to the right, and writing F in the data field of the initial C node.

like image 120
Vlad Avatar answered Dec 19 '22 17:12

Vlad


Obviously, It can't be done. If you need that capability, use a doubly-linked list. Otherwise, always pass along a pointer to the head of the list.

like image 26
David Schwartz Avatar answered Dec 19 '22 18:12

David Schwartz