题解 | #从单向链表中删除指定值的节点#
从单向链表中删除指定值的节点
https://www.nowcoder.com/practice/f96cd47e812842269058d483a11ced4f
class Node(object):
def __init__(self, item):
self.item = item
self.next = None
class SingleLinkList(object):
def __init__(self):
self._head = None
def is_empty(self):
return self._head is None
def length(self):
cur = self._head
count = 0
while cur is not None:
count += 1
cur = cur.next
return count
def add(self, item):
node = Node(item)
node.next = self._head
self._head = node
def append(self, item):
node = Node(item)
if self.is_empty():
self._head = node
else:
cur = self._head
while cur.next is not None:
cur = cur.next
cur.next = node
def items(self):
cur = self._head
while cur is not None:
yield cur.item
cur = cur.next
def insert(self, index, item):
if index <= 0:
self.add(item)
elif index > self.length() - 1:
self.append(item)
else:
node = Node(item)
cur = self._head
for _ in range(index - 1):
cur = cur.next
node.next = cur.next
cur.next = node
def index(self, item):
i = 0
for it in self.items():
if item == it:
break
i += 1
return i
def remove(self, item):
cur = self._head
pre = None
while cur is not None:
if cur.item == item:
if not pre:
self._head = cur.next
else:
pre.next = cur.next
return True
else:
pre = cur
cur = cur.next
if __name__ == "__main__":
s = list(map(int, input().split()))
head_num = s[1]
del_num = s[-1]
s = s[2:-1]
l = SingleLinkList()
head_node = Node(head_num)
l._head = head_node
for i in range(0, len(s) - 1, 2):
l.insert(l.index(s[i + 1]) + 1, s[i])
l.remove(del_num)
for item in l.items():
print(item, end=" ")

