Last active
August 29, 2015 14:03
-
-
Save habina/1effe686ec65dbadf1ec to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
""" | |
============================================================================ | |
Question : Implement an algorithm to delete a node in the middle of a singly linked list, given only access to that node. | |
EXAMPLE | |
Input: the node c from the linked list a->b->c->d->e | |
Result: nothing isreturned, but the new linked list looks like a- >b- >d->e | |
Solution : Copy the following pointer content, and relink the next to the next next pointer | |
Time Complexity : O(1) | |
Space Complexity: O(1) | |
Gist Link : https://gist.github.com/habina/1effe686ec65dbadf1ec | |
============================================================================ | |
""" | |
import random | |
class Node: | |
def __init__(self, value=None, next=None): | |
self.value = value | |
self.next = next | |
def __str__(self): | |
return chr(self.value) | |
def print_linkedList(node): | |
while node: | |
print(node) | |
node = node.next | |
def initialize_linkedList(n): | |
random.seed() | |
head = Node(random.randint(97, 122), 0) | |
n -= 1 | |
current = head | |
while(n > 0): | |
temp = Node(random.randint(97, 122), 0) | |
current.next = temp | |
current = temp | |
n -= 1 | |
return head | |
def deleteNode(node): | |
tempNode = node.next | |
node.value = tempNode.value | |
node.next = tempNode.next | |
a = initialize_linkedList(10) | |
print("Linked List:") | |
print_linkedList(a) | |
b = a.next.next | |
deleteNode(b) | |
print("After Delete Node:") | |
print_linkedList(a) | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment