#刷题 给出一个链表 输出中间节点
下面展示一些 内联代码片
。
def outputMiddleElementForLinkedList(head,k):
if head == None:
return False
else:
list = []
while head: #head指向头节点,遍历每个节点,然后放入一个列表中
list.append(head)
head = head.next
index = len(list)-1
index = index // 2 + 1
print(list[index])
方法二:
def outputMiddleElementForLinkedList(head,k):
count = 0
tem = head
while tem:
count += 1
temp = temp.next
count = count // 2 + 1
while count > 1: # 0 改成 1
count -= 1
head = head.next #假如三个数,count=2, count >1 ,循环一次即可。head是头节点,循环多一次就是第二节点。
return head