1.单链表数据结构(后续每个程序开始均需先定义单链表结构,我就省略不重复写了)
class LNode(object):
def __new__(self,x):
#数据域
self.data =x
#链接域
self.next =None
2.根据输入利用循环构建单链表,针对输入数据不是链表的问题,这里假设输入是列表
#创建链表
def constructListNode(array):
if len(array) == 0:
return None
head = Node()
head.val = array[0]
# 暂存头结点
res = head
for i in range(1, len(array)):
temp = Node()
temp.val = array[i]
#指向下一个结点
head.next = temp
#移动到下一个结点
head = temp
return res
3.遍历链表
# 遍历单链表
def ergodicListNode(head):
while head:
print(head.val, end = ' ')
head = head.next
4.反转链表
#反转链表
def reverseListNode(head):
if not head or not head.next:
return None
#构建前置结点
pre =head
#构建当前结点
cur =head.next
#存放当前节点的下一个结点
next = Node()
while cur:
#存放下一个结点
next =cur.next
#反转,改变指向
cur.next = pre
#向后移动,继续反转
pre =cur
cur =next
head.next =None
return pre
5.访问链表中的第K个结点
#访问链表中的第K个结点
def findK(head,k):
cur = head
while k>1:
cur = cur.next
k-=1
return cur
6.在链表前端添加元素
#add在链表前面添加元素
def add(value,head):
#创建一个节点
newnode = Node(value,None)
#添加在链表前面
newnode.next = head
head = newnode
return head
7.在链表尾部添加元素
#在链表尾部添加元素
def addtail(value,head):
#链表为空表时,则将添加的元素设为第一个元素
if head is None:
head = Node(value,None)
#创建一个新结点
newcode = Node(value,None)
#前置结点
pre =head
#当前结点
cur =head.next
#循环遍历至末尾,当cur指向None时,pre为链表最后一个结点
while cur:
pre = cur
cur = cur.next
#在末尾添加元素
pre.next =newcode
return head
8.搜索某元素是否在链表中
#搜索某元素是否在链表中
def search(head,m):
cur = head
while cur:
if m == cur.val:
return True
else:
cur =cur.next
return False
9.删除链表中的某项元素
#计算链表长度
def Nodelen(head):
count=0
while head:
count +=1
head =head.next
return count
#删除链表中的某项元素
def remove(head,n):
#空链表
if head is None:
return 0
#n的范围超过链表长度或为负
if n<0 or n>Nodelen(head):
return 0
#找到索引为n的结点
cur=head
while n>1:
pre =cur
cur =cur.next
n-=1
#找到第n个结点,删除当前结点
pre.next = cur.next
cur=None
return head