题解 | #【模板】链表#
【模板】链表
https://www.nowcoder.com/practice/97dc1ac2311046618fd19960041e3c6f
首先创建一个空列表,作为我们初始的链表
通过input接收n,记得转化为int类型
设计两个函数insert和delete
我们所需要用到的主要知识点就是对列表元素查找指定位置,获取位置下标进行插入删除操作
所以插入的核心代码是
def insert(x,y): if x not in Linklist: Linklist.append(y) else: loc = Linklist.index(x) Linklist.insert(loc,y)删除的核心代码是
def delete(x): if x in Linklist: loc = Linklist.index(x) Linklist.pop(loc)最后输出列表的内容,而不是输出整个列表:
if len(LinkList)==0: print('NULL') else: for i in LinkList: print(i,end=' ')完整代码如下:
def insert(x,y): if x not in Linklist: Linklist.append(y) else: loc = Linklist.index(x) Linklist.insert(loc,y) def delete(x): if x in Linklist: loc = Linklist.index(x) Linklist.pop(loc) n = int(input()) Linklist = [] while n>0: s = input() s = s.split(" ") x = s[1] x = int(x) if s[0] == 'insert': y = s[2] y = int(y) insert(x,y) else: delete(x) n = n-1 if len(Linklist) == 0: print("NULL") else: for i in Linklist: print(i,end=' ')