Skip to content

Instantly share code, notes, and snippets.

@humbroll
Created August 14, 2016 06:04
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save humbroll/afc43c4949a19173bff75fa195036f12 to your computer and use it in GitHub Desktop.
Save humbroll/afc43c4949a19173bff75fa195036f12 to your computer and use it in GitHub Desktop.
Delete middle node in LinkedList
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Question.
# Write code to remove duplicates from an unsorted linked list.
# Follow UP
# How would you solve this problem if a temporary buffer is not allowed?
class Node:
def __init__(self, value, next=None):
self.value = value
self.next_ptr = next
def __str__(self):
return "%d" % (self.value)
class LinkedList:
def __init__(self):
self.edge_node = None
def add_node(self, node):
self.edge_node = node
def add(self, node_value):
new_node = Node(node_value, self.edge_node)
self.add_node(new_node)
return new_node
def delete_node(self, node):
pre_node = None
cur_node = self.edge_node
while cur_node:
if cur_node == node:
if cur_node == self.edge_node:
self.edge_node = cur_node.next_ptr
else:
pre_node.next_ptr = cur_node.next_ptr
else:
pre_node = cur_node
cur_node = cur_node.next_ptr
def __str__(self):
node_value_arr = []
node = self.edge_node
while node:
node_value_arr.append(str(node))
node = node.next_ptr
return " -> ".join(node_value_arr)
if __name__ == '__main__':
# Setup linkedlist
linked_list = LinkedList()
node_5 = linked_list.add(5)
node_4 = linked_list.add(4)
node_3 = linked_list.add(3)
node_2 = linked_list.add(2)
node_1 = linked_list.add(1)
print "Before delete node"
print linked_list
linked_list.delete_node(node_1)
print "After delete node"
print linked_list
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment