时间:2021-07-01 10:21:17 帮助过:3人阅读
class Node(object):
def __init__(self, value, nextnode=None):
self.value = value
self._nextnode = nextnode
def append(self, n):
if not isinstance(n, Node):
n = Node(n)
self._nextnode, n = n, self._nextnode
self._nextnode._nextnode = n
Python里直接用dict套dict就可以表示图,graph[u][v]=w,表示从u到v的有向边,边权(或者其他需要标记的信息)为w。class TreeNode:
# 类的结构已经包含了指向关系
def __init__(self, x):
self.val = x
self.left = None
self.right = None
l1 = TreeNode(0)
l2 = TreeNode(1)
l3 = TreeNode(2)
# 引用表示指向关系
l1.left = l2
l1.right = l3
这个可以怒答一发,因为刚用java实现了一下链表,这里针对java和链表,python不发表意见private class Node {
public Node next;
public T data;
public Node(T d,Node n) {data = d; next = n;}
}
java的引用就不说了,python里所有的变量其实都是对象的引用(连基本类型都是如此),而这个引用,说白了就是个指向实例的指针。# -*- coding: utf-8 -*-
class Node(object):
def __init__(self, datum, next):
self.__datum = datum
self.__next = next
@property
def datum(self):
return self.__datum
@property
def next(self):
return self.__next
@next.setter
def next(self, next):
self.__next = next
class LinkedList(object):
def __init__(self):
self.__head = None
self.__tail = None
@property
def head(self):
return self.__head
@property
def tail(self):
return self.__tail
def purge(self):
self.__head = None
self.__tail = None
def is_empty(self):
return self.__head is None
def append(self, item):
#Generates the node.
datum = Node(item, None)
#For the first node in a linked list, it will change the head.
if self.__head is None:
self.__head = datum
else:
self.__tail.next = datum
self.__tail = datum
def remove(self, item):
pointer = self.__head
prepointer = None
#Finds the item
while pointer and pointer.datum != item:
prepointer = pointer
pointer = pointer.next
#Raise the error when not finding the item.
if pointer is None: raise KeyError
#When the linked list has one node, it will sets the head.
if pointer == self.__head:
self.__head = pointer.next
else:
prepointer.next = pointer.next
if pointer == self.__tail:
self.__tail = prepointer
其实完全不用指针也可以实现这种结构。