打出如下代码如果输入为"Empty", 则根据表是否为空输出"Empty"或 "Not empty"。 如果输入为"Length",则输出表长。 如果输入为"Insert i e",插入失败则输出"Insert failed",否则在i位置插入e后输出插入后表中的所有元素。 具体参见样例。
时间: 2023-05-30 13:01:21 浏览: 65
```python
class Node:
def __init__(self, val=0, next=None):
self.val = val
self.next = next
class MyLinkedList:
def __init__(self):
"""
Initialize your data structure here.
"""
self.head = None
self.size = 0
def get(self, index: int) -> int:
"""
Get the value of the index-th node in the linked list. If the index is invalid, return -1.
"""
if index < 0 or index >= self.size:
return -1
cur = self.head
for i in range(index):
cur = cur.next
return cur.val
def addAtHead(self, val: int) -> None:
"""
Add a node of value val before the first element of the linked list. After the insertion, the new node will be the first node of the linked list.
"""
self.head = Node(val, self.head)
self.size += 1
def addAtTail(self, val: int) -> None:
"""
Append a node of value val to the last element of the linked list.
"""
if self.size == 0:
self.head = Node(val)
else:
cur = self.head
while cur.next:
cur = cur.next
cur.next = Node(val)
self.size += 1
def addAtIndex(self, index: int, val: int) -> None:
"""
Add a node of value val before the index-th node in the linked list. If index equals to the length of linked list, the node will be appended to the end of linked list. If index is greater than the length, the node will not be inserted.
"""
if index > self.size:
print("Insert failed")
return
if index <= 0:
self.addAtHead(val)
elif index == self.size:
self.addAtTail(val)
else:
cur = self.head
for i in range(index-1):
cur = cur.next
cur.next = Node(val, cur.next)
self.size += 1
def deleteAtIndex(self, index: int) -> None:
"""
Delete the index-th node in the linked list, if the index is valid.
"""
if index < 0 or index >= self.size:
return
if index == 0:
self.head = self.head.next
else:
cur = self.head
for i in range(index-1):
cur = cur.next
cur.next = cur.next.next
self.size -= 1
if __name__ == '__main__':
linkedList = MyLinkedList()
while True:
try:
s = input().split()
if s[0] == 'Empty':
if linkedList.size == 0:
print('Empty')
else:
print('Not empty')
elif s[0] == 'Length':
print(linkedList.size)
elif s[0] == 'Insert':
i = int(s[1])
e = int(s[2])
linkedList.addAtIndex(i, e)
cur = linkedList.head
for i in range(linkedList.size):
print(cur.val, end=' ')
cur = cur.next
print()
except EOFError:
break
```