python进阶练习之——反向输出链表❤️
Posted 肥学大师
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了python进阶练习之——反向输出链表❤️相关的知识,希望对你有一定的参考价值。
**题目:**反向输出一个链表。
class Node:
def __init__(self, data):
self.data = data
self.next = None
def get_data(self):
return self.data
class List:
def __init__(self, head):
self.head = head
def is_empty(self):
return self.get_len() == 0
def get_len(self):
length = 0
temp = self.head
while temp is not None:
length += 1
temp = temp.next
return length
def append(self, node):
temp = self.head
while temp.next is not None:
temp = temp.next
temp.next = node
def delete(self, index):
if index < 1 or index > self.get_len():
print("给定位置不合理")
return
if index == 1:
self.head = self.head.next
return
temp = self.head
cur_pos = 0
while temp is not None:
cur_pos += 1
if cur_pos == index-1:
temp.next = temp.next.next
temp = temp.next
def insert(self, pos, node):
if pos < 1 or pos > self.get_len():
print("插入结点位置不合理")
return
temp = self.head
cur_pos = 0
while temp is not Node:
cur_pos += 1
if cur_pos == pos-1:
node.next = temp.next
temp.next =node
break
temp = temp.next
def reverse(self, head):
if head is None and head.next is None:
return head
pre = head
cur = head.next
while cur is not None:
temp = cur.next
cur.next = pre
pre = cur
cur = temp
head.next = None
return pre
def print_list(self, head):
init_data = []
while head is not None:
init_data.append(head.get_data())
head = head.next
return init_data
if __name__=='__main__':
head=Node('head')
link=List(head)
for i in range(10):
node=Node(i)
link.append(node)
print(link.print_list(head))
print(link.print_list(link.reverse(head)))
📣小白练手专栏,适合刚入手的新人欢迎订阅编程小白进阶
📣有什么不明白的欢迎私信或留言,得到细致讲解。另外想要进阶的朋友可以关注练手项目专栏
📣另外想学JavaWeb进厂的同学可以看看这个专栏:传送们
以上是关于python进阶练习之——反向输出链表❤️的主要内容,如果未能解决你的问题,请参考以下文章