具体算法为:
⑴找到链表的中点
⑵将链表的右半段反转
⑶将链表左半段和反转后的右半段合并
⑷按顺序输出每组队员编号
小胡编写程序实现将这n人进行分组并输出每组队员编号,请在划线处填入合适的代码。
# 找到原链表的中点
def middleNode(head):
slow = fast = head
while a[fast][1] != -1 and a[a[fast][1]][1] != -1:
slow =
fast = a[a[fast][1]][1]
return slow
# 将原链表的右半段反转
def reverseList(head):
pre = -1
cur = head
while cur != -1:
nextTemp = a[cur][1]
a[cur][1] = pre
cur = nextTemp
return pre
# 将原链表的两段合并
def mergeList(h1, h2):
while h1 != -1 and h2 != -1:
h1_tmp = a[h1][1]
h2_tmp = a[h2][1]
h1 = h1_tmp
a[h2][1] = h1
h2 = h2_tmp
# 输出分组情况
def show():
head = 0
i = 0
print('分组情况:')
while head != -1:
if i % 2 == 0:
print('第', , '组:', a[head][0], '和 ', end='')
else:
print(a[head][0])
i += 1
head = a[head][1]
# 读入n人编号,并按个人篮球赛成绩降序排序后依次将编号存入a中并输出a(代码略)
mid = middleNode(0)
head1 = 0
head2 = a[mid][1]
head2 = reverseList(head2)
mergeList(head1, head2)
show()