# -*- coding: utf-8 -*-
"""
Created on Thu Feb 28 16:44:36 2019
@author: CommissarMa
"""
class ListNode():
"""
结点类
"""
def __init__(self,value):
self.value=value#值
self.next=None#指向下一个结点的引用
class LinkedList():
"""
链表类(单向)
"""
def __init__(self):
self.headNode=None
self.tailNode=None
def add(self,value):
"""
在链表尾部添加结点
"""
if self.headNode==None:#第一次添加元素
listNode=ListNode(value)
self.headNode=listNode
self.tailNode=listNode
else:
listNode=ListNode(value)
self.tailNode.next=listNode
self.tailNode=self.tailNode.next
def delete(self,value):
"""
删除链表中第一次出现这个值的结点
"""
if self.headNode.value==value:#头节点就是该值的话,直接删除
if self.headNode==self.tailNode:
self.headNode=self.tailNode=self.headNode.next
else:
self.headNode=self.headNode.next
else:
node_preview=self.headNode
node=self.headNode.next
while node!=None:
if node.value==value:
node_preview.next=node.next
break
else:
node_preview=node
node=node.next
def find(self,value):
"""
查询在链表中是否存在该值,存在返回对应的结点,不存在返回None
"""
node=self.headNode
while node!=None:
if node.value==value:
return node
else:
node=node.next
return None
def print_list(self):
"""
打印链表中所有结点的值
"""
node=self.headNode
while node!=None:
print(node.value)
node=node.next
def print_list_reversely(self):
"""
逆序打印链表
"""
self.__print_list_reversely(self.headNode)
def __print_list_reversely(self,node):
"""
逆序打印链表
"""
if node!=None:
self.__print_list_reversely(node.next)
print(node.value)
if __name__=="__main__":
linkedList=LinkedList()#新建空链表
linkedList.add(1)
linkedList.add(2)
linkedList.add(3)
linkedList.add(4)
linkedList.add(5)
linkedList.add(6)
linkedList.delete(3)
linkedList.print_list()
print(linkedList.find(7))
linkedList.print_list_reversely()