Python ListNode学习
2020-02-26 本文已影响0人
陈忠俊
class Node:
def __init__(self, value, nextN = None):
self.value = value
self.nextN = nextN
class MyChainNode:
def __init__(self, head):
self.head = head
def append(self, node):
pointer = self.head
while pointer.nextN is not None:
pointer = pointer.nextN
pointer.nextN = node
@property
def getNodeLength(self):
pointer = self.head
length = 0
while pointer.nextN is not None:
length += 1
pointer = pointer.nextN
return length + 1
def insert(self, index, node):
if index < 1 or index > self.getNodeLength:
raise ValueError("index should greater than 1 and less than node length")
else:
pointer = self.head
cur_pos = 0
while cur_pos <= index - 1:
pointer = pointer.nextN
cur_pos += 1
node.nextN = pointer.nextN
pointer.nextN = node
def delete(self, index):
if index < 1 or index > self.getNodeLength:
raise ValueError("Index should greater than 1 and less than node_list length")
else:
pointer = self.head
cur_pos = 0
while cur_pos <= index - 1:
pointer =pointer.nextN
cur_pos += 1
pointer.nextN = pointer.nextN.nextN
def printAllNode(self):
pointer = self.head
for i in range(self.getNodeLength):
print("key: ", pointer.value)
pointer = pointer.nextN
具体用法
>>> from node import *
>>> head = Node(0)
>>> node1 = Node(1)
>>> node2 = Node(2)
>>> mynode = MyChainNode(head)
>>> mynode.append(node1)
>>> mynode.append(node2)
>>> mynode.printAllNode()
key: 0
key: 1
key: 2
>>> node4 = Node(4)
>>> mynode.insert(2, node4)
>>> mynode.printAllNode()
key: 0
key: 1
key: 2
key: 4
>>> node3= Node(3)
>>> mynode.insert(2,node3)
>>> mynode.printAllNode()
key: 0
key: 1
key: 2
key: 3
key: 4