Javatpoint Logo
Javatpoint Logo

Q. Program to search an element in a doubly linked list

Explanation

In this program, we need to search a given node in a doubly linked list.

Program to search an element in a doubly linked list

To solve this problem, we will traverse through the list using a node current. Current points to head and start comparing searched node data with current node data. If they are equal, set the flag to true and print the message along with the position of the searched node.

For, eg. In above list, a search node says 4 can be found at the position 3.

Algorithm

  1. Define a Node class which represents a node in the list. It will have three properties: data, previous which will point to the previous node and next which will point to the next node.
  2. Define another class for creating a doubly linked list, and it has two nodes: head and tail. Initially, head and tail will point to null.
  3. addNode() will add node to the list:
    1. It first checks whether the head is null, then it will insert the node as the head.
    2. Both head and tail will point to a newly added node.
    3. Head's previous pointer will point to null and tail's next pointer will point to null.
    4. If the head is not null, the new node will be inserted at the end of the list such that new node's previous pointer will point to tail.
    5. The new node will become the new tail. Tail's next pointer will point to null.
  4. searchNode() will search for a node in the list:
    1. Variable i will keep track of the position of the searched node.
    2. The variable flag will store boolean value false.
    3. Current will point to head node.
    4. Iterate through the loop by incrementing current to current.next and i to i + 1.
    5. Compare each node's data with the searched node. If a match is found, set flag to true.
    6. If the flag is true, prints the position of the searched node.
    7. Else, print the message "Element is not present in the list".

Solution

Python

Output:

Node is present in the list at the position : 3
Node is not present in the list

C

Output:

Node is present in the list at the position : 3
Node is not present in the list

JAVA

Output:

Node is present in the list at the position : 3
Node is not present in the list

C#

Output:

Node is present in the list at the position : 3
Node is not present in the list

PHP

Output:

Node is present in the list at the position : 3
Node is not present in the list

Next Topic#




Please Share

facebook twitter google plus pinterest

B.Tech / MCA


Learn Latest Tutorials