Skip to content

Q2.3 Delete middle node #316

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
24 changes: 24 additions & 0 deletions cracking_the_code/chapter2/Q2.3_delete_middle_node.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
import logging
from linked_list import *


# We can simply copy the value of next node to the current node and delete next node
def delete_middle_node(node):
if not node:
return
node.value = node.next.value
node.next = node.next.next


def main():
# build a list
lst = LinkedList(['a', 'b', 'c', 'd', 'e', 'f'])
p = lst.head()
while p.value != 'c':
p = p.next
delete_middle_node(p)
lst.print()


if __name__ == '__main__':
main()
19 changes: 11 additions & 8 deletions cracking_the_code/chapter2/linked_list.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ def __init__(self, v):


class LinkedList:
head = None
_head = None

def __init__(self, lst=None):
if isinstance(lst, list):
Expand All @@ -20,8 +20,8 @@ def __eq__(self, other):
return False
if self.length() != other.length():
return False
n = self.head
m = other.head
n = self._head
m = other._head
while n:
if n.value != m.value:
return False
Expand All @@ -30,18 +30,18 @@ def __eq__(self, other):
return True

def length(self):
n = self.head
n = self._head
count = 0
while n:
count += 1
n = n.next

def add(self, v):
new = Node(v)
if not self.head:
self.head = new
if not self._head:
self._head = new
return
p = self.head
p = self._head
while p.next:
p = p.next
p.next = new
Expand All @@ -51,11 +51,14 @@ def list_to_linkedlist(self, lst):
self.add(item)

def print(self):
p = self.head
p = self._head
str_lst = ''
if not p:
print('[]')
while p:
str_lst += '{}->'.format(p.value)
p = p.next
print(str_lst)

def head(self):
return self._head