Get the Node from Linked List

Implement the function for the ChatHandler class to retrieve a node from the linked list.

Introduction

We've already implemented the class to construct our chat list data structure and implemented functions to get the current time, and to create nodes to store the user's name, image, and message. Each user will be denoted by an id, which is an index of the user's name in the chat_names array. Every time a new message is generated, the chat of that particular user needs to become the head of the linked list so that the user's new message appears at the top of the chat list. Now let's implement another utility function to get a node from the linked list for a particular id using the hashmap.

Understand the implementation

Here are the steps we'll need to complete to get the node from the linked list and update the pointers of its previous and next nodes (if present).

  1. We'll retrieve the node from the hashmap using the id. In the hashmap, we will store the id of the user and the corresponding node, which together act as a key-value pair.

  2. We'll store the previous and the next node's address/pointer as prevNode and nextNode.

  3. We'll then update the prevNode's next pointer to nextNode (because we need to take out the current node from the linked list and point the previous node to the next node of the current node).

  4. Similarly, we'll update the nextNode's prev pointer to prevNode (because we need to take out the current node from the linked list and point the next node to the previous node of the current node).

  5. We'll set the next and prev of the current node to null.

  6. We'll return the current node.

Let's look at the implementation:

Get hands-on with 1400+ tech skills courses.