题目描述
Given a singly linked list L: L0→L1→…→Ln-1→Ln,
reorder it to: L0→Ln→L1→Ln-1→L2→Ln-2→…
You may not modify the values in the list’s nodes, only nodes itself may be changed.
举个例子:
0 1 2 3 4 ----> 0 4 1 3 2
0 1 2 3 ----> 0 3 2 1
解题思路
最简单的方式就是通过一个列表保存所有node节点, 然后根据节点个数是奇数还是偶数, 按照题目规则得到一个序列, 根据这个序列重新链接整个链表.
代码
class Solution(object):
def reorderList(self, head):
nodeList = [] #store all the node
node = head
while node != None:
nodeList.append(node)
node = node.next
lenth = len(nodeList)
# if the lenth is even: 0->3->1->2-null
if lenth % 2 == 0:
for i in range(lenth/2):
nodeList[i].next = nodeList[lenth-1-i]
if i+1 >= lenth/2:
nodeList[lenth-1-i].next = None
else:
nodeList[lenth-1-i].next = nodeList[i+1]
# else if the lenth is odd: 0->4->1->3->(2)->null
else:
for i in range(lenth//2+1):
if i == lenth//2:
nodeList[i].next = None
else:
nodeList[i].next = nodeList[lenth-1-i]
nodeList[lenth-1-i].next = nodeList[i+1]