题解 | #【模板】链表#
【模板】链表
https://www.nowcoder.com/practice/97dc1ac2311046618fd19960041e3c6f
# class Stack: # def __init__(self, val = None): # self.val = val # self.next = None # phead = Stack() # num = input() # for i in range(int(num)): # line = input().split() # x = int(line[1]) # cur = phead # if line[0][0] == 'i': # y = int(line[2]) # while cur and cur.val and cur.val !=x: # cur = cur.next # if not cur: # cur = Stack(y) # elif not cur.val: # cur.val = y # elif not cur.next: # cur.next = Stack(y) # else: # cur2 = cur.next # cur.next = Stack(y) # cur.next.next = cur2 # else: # if cur.val and cur.val == x: # phead = cur.next # else: # while cur.next: # if cur.next.val == x: # cur.next = cur.next.next # while phead: # print(phead.val,end = ' ') # phead = phead.next # 摆烂了,直接数组 s = [] n = int(input()) for i in range(n): a = input() if a[0] == 'i': a = a.split() x = int(a[1]) y = int(a[2]) if len(s) == 0: s = [y] else: cur = 0 for j in range(len(s)): cur = j if s[j] == x: s.insert(j,y) break if cur == len(s) - 1: s.append(y) else: a = a.split() x = int(a[1]) for j in range(len(s)): if s[j] == x: s.pop(j) break if len(s) == 0: print('NULL') else: for j in range(len(s)): print(s[j],end = ' ')
看了一下别人写的:
link = []
fori in range(int(input())):
ipt = input().split()
ifipt[0] == 'insert':
x,y = int(ipt[1]),int(ipt[2])
ifx in link:
link.insert(link.index(x),y)
else:
link.append(y)
ifipt[0] == 'delete':
x = int(ipt[1])
ifx in link:
link.remove(x)
print('NULL') ifnot link else[print(i,end=' ') fori in link]
这也太强了,学到新知识了,可以if i in Link这种语句,高效的去查找。学会了。
#日常刷题#