美文网首页
Python ListNode学习

Python ListNode学习

作者: 陈忠俊 | 来源:发表于2020-02-26 20:15 被阅读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

相关文章

网友评论

      本文标题:Python ListNode学习

      本文链接:https://www.haomeiwen.com/subject/vglwchtx.html