Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

given a node how can I find previous node in a singly linked list

Given the current node, how can I find its previous node in a Singly Linked List. Thanks. Logic will do , code is appreciated. We all know given a root node one can do a sequential traverse , I want to know if there is a smarter way that avoids sequential access overhead. (assume there is no access to root node) Thanks.

like image 661
David Prun Avatar asked Aug 25 '11 23:08

David Prun


People also ask

How do you find a previous node in a singly linked list?

You can't. Singly-linked lists by definition only link each node to its successor, not predecessor. There is no information about the predecessor; not even information about whether it exists at all (your node could be the head of the list). You could use a doubly-linked list.

How do I find the second last node in a linked list?

The idea is to traverse the linked list following the below approach: If the list is empty or contains less than 2 elements, return false. Otherwise, check if the current node is the second last node of the linked list or not. That is, if (current_node->next-next == NULL ) then the current node is the second last node.

How do I point to previous node JS?

But if you need to maintain a pointer to the node previous to the current node in your search, a simple way is to check if node->NEXT is the node you're looking for. Then node is your prev , node->NEXT is your current , and node->NEXT->NEXT is your next .

What will be the address part of last node in a singly linked list?

The first node is always used as a reference to traverse the list and is called HEAD. The last node points to NULL.


1 Answers

If you want to delete the current node, you can do that without finding previous node as well.

Python Code:

def deleteNode(self, node):

node.val = node.next.val

node.next = node.next.next

@ Delete Node in a Linked List

like image 55
ayush_manglani Avatar answered Sep 23 '22 13:09

ayush_manglani