链表是一种物理存储单元上非连续、非顺序的存储结构,数据元素的逻辑顺序是通过链表中的指针链接次序实现的。链表由一系列结点(链表中每一个元素称为结点)组成,结点可以在运行时动态生成。每个结点包括两个部分:一个是存储数据元素的数据域,另一个是存储下一个结点地址的指针域。
因此要想实现链表,必须先定义结点node类。
class Node:
def __init__(self,initdata):
self.data = initdata
self.next = None
def getData(self):
return self.data
def getNext(self):
return self.next
def setData(self,newdata):
self.data = newdata
def setNext(self,newnext):
self.next = newnext
接着便可以定义Linklist类,linklist的属性只有一个,那就是头结点,头结点并不是一个具体的node对象,而是类似于一个空指针,指向链表中第一个node,有了头结点便可以根据node的指针找到所有的元素。
class LinkList:
def __init__(self):
self.head = None
def isEmpty(self):
'''判断是否为空'''
return self.head == None
def locate(self,index):
'''找到索引位置为index的node'''
if self.isEmpty():
raise IndexError("链表为空")
p = self.head
j = 0
while (p != None and j < index):
j += 1
p = p.next
if (j == index):
return p
else:
return None
def add(self,data):
'''在链表头处添加node'''
# 在链表头处添加node
temp = Node(data)
temp.setNext(self.head)
self.head = temp
def length(self):
'''返回链表长度'''
return self.length
def insert(self,data,loc):
'''在链表中的loc位置出插入node,值为data'''
preNode = self.locate(loc-1)
if preNode != None:
newNode = Node(data)
newNode.next = preNode.next
preNode.next = newNode
else:
raise IndexError("插入失败")
def delete(self, loc):
'''删除链表中loc位置处的node'''
preNode = self.locate(loc-1)
if preNode != None:
delNode = preNode.next
preNode.next = delNode.next
return delNode
else:
raise IndexError("删除失败")
def search(self,data):
'''查询链表中是否存在元素data'''
current = self.head
found = False
while current != None and not found:
if current.data == data:
found = True
else:
current = current.next
return found
def remove(self,data):
'''删除链表中的data元素'''
current = self.head
previous = None
found = False
while not found:
if current.data == data:
found = True
else:
previous = current
current = current.next
if previous == None: #如果要删除第一个元素
self.head = current.next
else:
previous.next = current.next
def show(self):
'''输出链表'''
result = "head"
current = self.head
while current != None:
data = current.data
result = result + "--->" +str(data)
current = current.next
return result