Skip to content

Commit

Permalink
Merge pull request wangzheng0822#162 from Danielyan86/master
Browse files Browse the repository at this point in the history
[Python]增加链表部分for遍历方法,调整代码格式
  • Loading branch information
wangzheng0822 authored Nov 23, 2018
2 parents 81cea36 + b2861ce commit 06a0031
Showing 1 changed file with 23 additions and 15 deletions.
38 changes: 23 additions & 15 deletions python/06_linkedlist/singly_linked_list.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,23 +6,23 @@
"""
from typing import Optional


class Node:
def __init__(self, data: int, next=None):

def __init__(self, data: int, next_node=None):
self.data = data
self._next = next
self._next = next_node


class SinglyLinkedList:

def __init__(self):
self._head = None

def find_by_value(self, value: int) -> Optional[Node]:
p = self._head
while p and p.data != value:
p = p._next

return p

def find_by_index(self, index: int) -> Optional[Node]:
Expand All @@ -31,22 +31,21 @@ def find_by_index(self, index: int) -> Optional[Node]:
while p and position != index:
p = p._next
position += 1

return p

def insert_value_to_head(self, value: int):
new_node = Node(value)
self.insert_node_to_head(new_node)

def insert_node_to_head(self, new_node: Node):
if new_node:
new_node._next = self._head
self._head = new_node

def insert_value_after(self, node: Node, value: int):
new_node = Node(value)
self.insert_node_after(node, new_node)

def insert_node_after(self, node: Node, new_node: Node):
if not node or not new_node:
return
Expand All @@ -66,7 +65,7 @@ def insert_node_before(self, node: Node, new_node: Node):
current = self._head
while current._next and current._next != node:
current = current._next
if not current._next: # node is not even in the list
if not current._next: # node is not even in the list
return
new_node._next = node
current._next = new_node
Expand All @@ -83,13 +82,13 @@ def delete_by_node(self, node: Node):
while current and current._next != node:
current = current._next
if not current: # node not in the list
return
return
current._next = None

def delete_by_value(self, value: int):
if not self._head or not value:
return
fake_head = Node(value+1)
fake_head = Node(value + 1)
fake_head._next = self._head
prev, current = fake_head, self._head
while current:
Expand All @@ -100,7 +99,7 @@ def delete_by_value(self, value: int):
if prev._next:
prev._next = None
self._head = fake_head._next # in case head.data == value

def __repr__(self) -> str:
nums = []
current = self._head
Expand All @@ -112,6 +111,13 @@ def __repr__(self) -> str:
else:
return ""

# 重写__iter__方法,方便for关键字调用打印值
def __iter__(self):
node = self._head
while node:
yield node.data
node = node._next

def print_all(self):
current = self._head
if current:
Expand All @@ -136,4 +142,6 @@ def print_all(self):
l.delete_by_node(node11)
l.delete_by_node(l._head)
l.delete_by_value(13)
print(l)
print(l)
for value in l:
print(value)

0 comments on commit 06a0031

Please sign in to comment.