{ "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "# Linked Lists" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "\n", "\n", "### Steps for creating a linked list:\n", "1. Create head and tail, initialize with null\n", "2. Create a blank node and assign a value to it and reference to null.\n", "3. Link head and tail with these nodes\n", "\n", "[head] -> [node] -> [tail]\n", "\n" ] }, { "cell_type": "code", "execution_count": 1, "metadata": {}, "outputs": [], "source": [ "class Node:\n", " def __init__(self, value):\n", " self.value = value\n", " self.next = None\n", "\n", "class LinkedList:\n", " def __init__(self):\n", " self.head = None\n", " self.tail = None\n", " self.next = None" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Adding an element inside a linked list" ] }, { "cell_type": "code", "execution_count": 2, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "[1, 4, 3, 2, 0]\n" ] } ], "source": [ "class Node:\n", " def __init__(self, value = None):\n", " self.value = value\n", " self.next = None\n", "\n", "class LinkedList:\n", " def __init__(self):\n", " self.head = None\n", " self.tail = None\n", " self.next = None\n", "\n", " def __iter__(self):\n", " node = self.head\n", " while node:\n", " yield node\n", " node = node.next\n", "\n", " def __insert__(self, value, location = None):\n", " new_node = Node(value)\n", " if self.head is None:\n", " self.head = new_node\n", " self.tail = new_node\n", "\n", " else:\n", "\n", " if location == 0:\n", " new_node.next = self.head\n", " self.head = new_node\n", "\n", " elif location == -1:\n", " new_node.next = None\n", " self.tail.next = new_node\n", " self.tail = new_node\n", "\n", " else:\n", " temp = self.head\n", " idx = 0\n", " while idx < location -1:\n", " temp = temp.next\n", " idx += 1\n", " next_node = temp.next\n", " temp.next = new_node\n", " new_node.next = next_node\n", " \n", " if temp == self.tail:\n", " self.tail = new_node\n", "\n", "\n", "linkedlist = LinkedList()\n", "linkedlist.__insert__(1, 1)\n", "linkedlist.__insert__(2, 1)\n", "linkedlist.__insert__(3, 1)\n", "linkedlist.__insert__(4, 1)\n", "linkedlist.__insert__(0, 4)\n", "\n", "print([node.value for node in linkedlist])" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [] } ], "metadata": { "interpreter": { "hash": "40d3a090f54c6569ab1632332b64b2c03c39dcf918b08424e98f38b5ae0af88f" }, "kernelspec": { "display_name": "Python 3.8.3 ('base')", "language": "python", "name": "python3" }, "language_info": { "codemirror_mode": { "name": "ipython", "version": 3 }, "file_extension": ".py", "mimetype": "text/x-python", "name": "python", "nbconvert_exporter": "python", "pygments_lexer": "ipython3", "version": "3.8.3" }, "orig_nbformat": 4 }, "nbformat": 4, "nbformat_minor": 2 }