""" =============================== 链表的常规操作 ====================================== https://blog.csdn.net/Blood_Seeker/article/details/78992722 """
class ListNode(object):
def __init__(self, x = None):
self.val = x
self.next = None
class LinkList(object):
def __init__(self):
self.head = None
def initList(self, dataList):
self.head = ListNode(None)
pTail = self.head
for i in dataList:
newNode = ListNode(i)
pTail.next = newNode
pTail = newNode
def isEmpty(self):
return self.head.next is None
def getLength(self):
if self.isEmpty():
exit(0)
p = self.head.next
len = 0
while p:
len += 1
p = p.next
return len
def traveList(self):
if self.isEmpty():
exit(0)
print ('link list traving result:')
p = self.head.next
while p:
print (p.val, end= " ")
p = p.next
def insertElem(self, val, index):
""" 在 第index个节点(p.next)之前插入"""
p = self.head
i = 1
while p and i < index:
p = p.next
i = i + 1
if p is None or i > index:
print("ERROR, 无法插入节点")
return False
pNew = ListNode(val)
pNew.next = p.next
p.next = pNew
def deleteElem(self, index):
"删除第index个节点(即删除 p.next节点)"
p = self.head
i = 1
while p.next and i < index:
p = p.next
i = i + 1
if p.next is None or i > index:
print("ERROR, 该节点不存在")
return False
delVal = p.next.val
print("deleted value:", delVal)
p.next = p.next.next
if __name__ == '__main__':
dataList = [1, 2, 3, 4, 5]
l = LinkList()
l.initList(dataList)
l.traveList()
print('\n')
print(l.getLength())
l.insertElem(666, 6)
l.traveList()
print('\n')
l.deleteElem(4)
l.traveList()
print('\n')
参考:
- 链表操作