Загрузка данных
# Класс узла
class Node:
def __init__(self, data):
self.data = data
self.next = None
# Класс однонаправленного списка
class LinkedList:
def __init__(self):
self.head = None
self.tail = None
self.size = 0
# 1. Добавить в конец
def add_end(self, data):
new = Node(data)
if self.head is None:
self.head = new
self.tail = new
else:
self.tail.next = new
self.tail = new
self.size += 1
# 2. Добавить в начало
def add_begin(self, data):
new = Node(data)
if self.head is None:
self.head = new
self.tail = new
else:
new.next = self.head
self.head = new
self.size += 1
# 3. Добавить в позицию (с 1)
def add_pos(self, data, pos):
if pos < 1 or pos > self.size + 1:
print("Неверная позиция")
return
if pos == 1:
self.add_begin(data)
return
if pos == self.size + 1:
self.add_end(data)
return
new = Node(data)
cur = self.head
for _ in range(pos - 2):
cur = cur.next
new.next = cur.next
cur.next = new
self.size += 1
# 4. Удалить по значению
def del_value(self, value):
cur = self.head
prev = None
while cur:
if cur.data == value:
if prev is None:
self.head = cur.next
else:
prev.next = cur.next
if cur == self.tail:
self.tail = prev
self.size -= 1
return
prev = cur
cur = cur.next
print("Элемент не найден")
# 5. Удалить по номеру
def del_pos(self, pos):
if pos < 1 or pos > self.size:
print("Неверная позиция")
return
cur = self.head
prev = None
for _ in range(pos - 1):
prev = cur
cur = cur.next
if prev is None:
self.head = cur.next
else:
prev.next = cur.next
if cur == self.tail:
self.tail = prev
self.size -= 1
# 6. Очистить
def clear(self):
self.head = None
self.tail = None
self.size = 0
print("Список очищен")
# 7. Найти номер элемента
def find(self, value):
cur = self.head
i = 1
while cur:
if cur.data == value:
return i
cur = cur.next
i += 1
return -1
# 8. Просмотр
def show(self):
if self.head is None:
print("Список пуст")
return
cur = self.head
s = ""
while cur:
s += str(cur.data) + " -> "
cur = cur.next
print(s + "None")
# ====== Основная программа (Вариант 1: предложение) ======
text = input("Введите предложение, оканчивающееся точкой:\n")
lst = LinkedList()
for ch in text: # добавляем каждый символ в конец
lst.add_end(ch)
print("\nИсходный список:")
lst.show()
while True:
print("\n1-Добавить в конец 2-Добавить в начало 3-Добавить в позицию")
print("4-Удалить по значению 5-Удалить по номеру 6-Очистить")
print("7-Найти номер 8-Просмотр 0-Выход")
c = input("Выбор: ")
if c == '1':
lst.add_end(input("Символ: "))
lst.show()
elif c == '2':
lst.add_begin(input("Символ: "))
lst.show()
elif c == '3':
lst.add_pos(input("Символ: "), int(input("Позиция: ")))
lst.show()
elif c == '4':
lst.del_value(input("Значение: "))
lst.show()
elif c == '5':
lst.del_pos(int(input("Номер: ")))
lst.show()
elif c == '6':
lst.clear()
lst.show()
elif c == '7':
n = lst.find(input("Значение: "))
print("Не найден" if n == -1 else f"Номер: {n}")
elif c == '8':
lst.show()
elif c == '0':
break
else:
print("Неверный выбор")