{ "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "## ``Q5.``##\n", "\n", "## ```Write a Python program to construct a linked list. Prompt the user for input. Remove any duplicate numbers from the linked list.``` ##" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## -----------------------------------------------------------------------------------------------------------------------------" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Problem Description ## \n", "\n", "In this program, we need to remove the duplicate nodes from the given singly linked list.\n", "\n", "**Original List:** \n", "\n", " \n", "\n", "**List after removing duplicate nodes:** \n", "\n", " \n", "\n", "In the above list, node 2 is repeated thrice, and node 1 is repeated twice. Node current will point to head, and index will point to node next to current. Start traversing the list till a duplicate is found that is when current's data is equal to index's data. In the above example, the first duplicate will be found at position 4. Assign current to another node temp. Connect temp's next node with index's next node. Delete index which was pointing to duplicate node. This process will continue until all duplicates are removed." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## -----------------------------------------------------------------------------------------------------------------------------" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Steps for removing duplicate number(s) from the linked list\n", "\n", "1. Create a class ```Node``` which has two data attributes: ```data``` and ```next```. The data attribute ```next``` points to the next node in the list.

\n", "\n", "2. Create another class ```LinkedList``` which has two data attributes: ```head``` and ```tail.```

\n", "\n", "3. The ```add_node()``` method will add a new node to the list: \n", " a. Create a new node. \n", " b. It first checks, whether the ```head``` is equal to null which means the list is empty. \n", " c. If the list is empty, both ```head``` and ```tail``` will point to a newly added node. \n", " d. If the list is not empty, the new node will be added to end of the list such that ```tail's``` next will point to a newly added node. This new node will become the new tail of the list.

\n", "\n", "4. The ```remove_duplicate()``` method will remove duplicate nodes from the list. \n", " a. Define a new node ```current``` which will initially point to head. \n", " b. Node ```temp``` will point to ```current``` and ```index``` will always point to node next to current. \n", " c. Loop through the list till ```current``` points to null. \n", " d. Check whether current's data is equal to index's data that means ```index``` is duplicate of ```current.``` \n", " e. Since index points to duplicate node so skip it by making node next to temp to will point to node next to index, i.e. ```temp.next = index.next.```