import re

class Node: def init(self, data=None): self.data = data self.next = None

class LinkedList: def init(self): self.head = None

def insert(self, data):
    new_node = Node(data)
    # 如果链表为空或数据小于头节点数据,则插入到开头
    if self.head is None or data < self.head.data:
        new_node.next = self.head
        self.head = new_node
    else:
        current = self.head
        # 找到合适的插入位置
        while current.next is not None and data > current.next.data:
            current = current.next
        new_node.next = current.next
        current.next = new_node

def traverse(self):
    current = self.head
    while current is not None:
        print(current.data, end=' ')
        current = current.next
    print()

def search(self, target):
    current = self.head
    while current is not None:
        if current.data == target:
            return 1
        current = current.next
    return 0

def get_input_sequence(): sequence = [] while True: try: input_str = input('请输入递增的整型元素序列,以空格分隔: ') sequence = re.findall(r'\d+', input_str) sequence = list(map(int, sequence)) if sorted(sequence) != sequence: raise ValueError break except ValueError: print('输入错误,请重新输入递增的整型元素序列!') return sequence

def main(): linked_list = LinkedList() sequence = get_input_sequence() for num in sequence: linked_list.insert(num) print('链表遍历结果:') linked_list.traverse()

target = int(input('请输入要查找的元素: '))
if linked_list.search(target):
    print('元素 {} 在链表中找到了。'.format(target))
else:
    print('元素 {} 不在链表中。'.format(target))

new_num = int(input('请输入要插入的元素: '))
linked_list.insert(new_num)
print('插入元素后的链表遍历结果:')
linked_list.traverse()

if name == 'main': main()

Python 链表基本操作练习:建立、遍历、查找、插入

原文地址: http://www.cveoy.top/t/topic/bLAw 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录