链表的增加,删除,插入,查找及打印。
#encoding=utf-8
class Node:
def __init__(self,value=None,next=None):
self.value = value
self.next = next
class LinkedList(object):
def __init__(self,head=None):
self.head = head
def __len__(self):
count =0
if self.head is None:
return count
node = self.head
while node:
count+=1
node = node.next
return count
def append(self,node):
if self.head is None:
self.head = node
else:
cur_node = self.head
while cur_node.next is not None:
cur_node = cur_node.next
cur_node.next = node
def find(self,value):
if self.head is None:
return None
else:
cur_node = self.head
while cur_node:
if cur_node.value == value:
return cur_node
cur_node = cur_node.next
return None
def delete(self,value):
if self.head is None:
return None
elif self.head.value == value:
tmp = self.head
self.head=self.head.next
return tmp
else:
cur_node = self.head
before_node = None
while cur_node:
if cur_node.value == value:
before_node.next=cur_node.next
return cur_node
before_node = cur_node
cur_node = cur_node.next
return None
def insert_front(self,data):
if self.head is None:
self.head = Node(data)
else:
tmp = self.head
self.head = Node(data)
self.head.next = tmp
return self.head
def get_all(self):
data = []
if self.head is None:
return data
else:
cur_node = self.head
while cur_node:
data.append(cur_node.value)
cur_node = cur_node.next
return data
a=LinkedList()
a.append(Node(1))
a.append(Node(2))
a.append(Node(3))
print(a.insert_front(4))
print(a.get_all())