难点在于需要自己构建数据结构 题目: 1、输入节点总个数、需要删除的倒数第k个节点和链表节点 2、当节点个数小于1时,返回"empty list!"
如: 输入为: 5 2 1 2 3 4 5 输出为: 1 2 3 5
class Node(object):
def __init__(self, val):
self.val = val
self.next = None
class Solution(object):
def remove_node(self, data, del_n):
n = len(data)
head = self.create_list(data)
target = n - del_n + 1
check = []
new_head = self.remove_n(head, target)
return new_head
def remove_n(self, head, target):
cur_num = 1
pre = head
cur = head.next
while cur:
if cur_num == target:
pre.next = cur.next
break
else:
cur = cur.next
pre = pre.next
cur_num += 1
return head
def create_list(self, data):
head = Node(0)
for i in range(len(data ) -1, -1, -1):
cur = Node(data[i])
cur.next = head.next
head.next = cur
return head
if __name__ == "__main__":
list_n = int(input())
del_n = int(input())
data = [int(i) for i in input().split()]
if list_n < 1:
print("empty list!")
else:
solu = Solution()
head = solu.remove_node(data, del_n)
cur = head.next
res = []
while cur:
res.append(str(cur.val))
cur = cur.next
print(" ".join(res))
|