'''定义单向链表'''
class listNode(object):
def __init__(self, val=0, next=None):
self.val = val
self.next = next
'''单向链表打印和反转'''
class processListNode():
# 打印单向链表
def printListNode(self, listNode):
while listNode:
if listNode.next == None:
print(listNode.val)
else:
print(listNode.val,'-->', end="")
listNode = listNode.next
# 反转单向链表
def reverseList(self, head):
if head == None or head.next==None: # 若链表为空或者仅一个数就直接返回
return head
pre = None
nextNode = None
while(head != None):
nextNode = head.next # 1
head.next = pre # 2
pre = head # 3
head = nextNode # 4
return pre
# 获取链表长度
def get_len(self,head):
n = 0
while head:
n += 1
head = head.next
return n
# 删除链表第k个元素
def removeNode(self, head, k):
if head == None or head.next == None: # 若链表为空或者仅一个数就直接返回空链表
return listNode()
if k > self.get_len(head): # 若k大于链表长度,直接返回链表
return head
node = head # 复制链表,让head一直指向头结点,利用node进行删除操作
if k == 1: # 删除头节点
node = node.next
return node
count = 2
while True:
if count == k:
node.next = node.next.next
break
else:
count += 1
node = node.next
return head
'''合并两个有序链表'''
class Solution():
def mergeTwoList(self, l1:listNode, l2:listNode)-> listNode:
if l1 == None:
return l2
if l2 == None:
return l1
if l1.val < l2.val:
l1.next = self.mergeTwoList(l1.next, l2)
return l1
else: # l1.val >= l2.val
l2.next = self.mergeTwoList(l1, l2.next)
return l2
numNode1 = [1,4,6,8]
numNode2 = [2,4,5,9]
'''构建链表'''
L = listNode()
for i in range(0, len(numNode1)):
if i == 0:
listNode1 = listNode(numNode1[i])
else:
listNode1 = listNode(numNode1[i], listNode1)
for i in range(0, len(numNode2)):
if i == 0:
listNode2 = listNode(numNode2[i])
else:
listNode2 = listNode(numNode2[i], listNode2)
'''反转单向链表'''
P = processListNode()
listNode1 = P.reverseList(listNode1)
listNode2 = P.reverseList(listNode2)
'''打印单向链表'''
print("listNode1:")
P.printListNode(listNode1)
print("listNode2:")
P.printListNode(listNode2)
'''合并两个单向链表'''
S = Solution()
listTwo = S.mergeTwoList(listNode1, listNode2)
print("listNodeTwo:")
P.printListNode(listTwo)
'''删除单向链表某个节点'''
listRemove = P.removeNode(listTwo,6)
print("删除第k个节点后的链表:")
P.printListNode(listRemove)
输出结果:
listNode1:
1 -->4 -->5 -->8
listNode2:
2 -->4 -->7 -->9
listNodeTwo:
1 -->2 -->4 -->4 -->5 -->7 -->8 -->9
删除第k个节点后的链表:
1 -->2 -->4 -->4 -->5 -->8 -->9
python单向链表定义、打印、反转、删除与合并
于 2022-03-22 13:55:50 首次发布