链表的常用操作

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
posted @ 2020-10-20 00:11  王钊  阅读(100)  评论(0)    收藏  举报