这里我的问题是我有一个1->2->3->4->5 的链接列表
我的概念是像1->5->2->4->3 一样打印它们
这意味着首先开始,然后结束
我该怎么做?
我有一个想法,首先我在空节点中取一个空节点,我将保留起始节点和
在那之后,我将遍历到最后一个,结束节点将保持在那里,此时我的大脑停止
有人能指导我做这件事吗?提前感谢
def mutate_linked_list(head):
#node creation
s = t = Node()
t.next = head
head = head.next
while head is None:
t.next = head
head = head.next
# here i used recursion concept
mutate_linked_list(head)
return head
但它不起作用。。。。
[head[0]]+[head[-1]] + head[1:-1]
def mutate_linked_list(head):
# return early for an size 1 list
if head.next is None:
return head
# find the last and penultimate nodes
penultimate = head
while penultimate.next.next is not None:
penultimate = penultimate.next
last = penultimate.next
# detach the last node from the end
penultimate.next = None
# prepend it to the second node
last.next = head.next.next
# and reconnect the head
head.next = last
return head
from collections import deque
def mutate_linked_list(head):
mydeque = deque(head)
try:
while True:
yield mydeque.popleft()
yield mydeque.pop()
except IndexError:
pass
for i in mutate_linked_list(range(1,6)):
print(i)
很明显,您可以创建一个列表并在其中添加.append,而不是生成值。
就像一个练习。。。
def mix(head):
# Walk to the end of the list
last = head
secondlast = None
while last.next:
secondlast = last
last = last.next
if secondlast:
# move last element to second place
secondlast.next = None
last.next = head.next
head.next = last
# mix the rest of the list (recursion)
mix(last.next)
关于:
from itertools import izip_longest
def mutate_linked_list(head):
m = len(head)/2 # Get the middle position
return [item for pair in izip_longest(head[:m+1], head[:m:-1])
for item in pair
if item is not None]
然后,你就可以出发了:
head = [1,2,3,4,5]
mutate_linked_list(head)
[1, 5, 2, 4, 3]
它还适用于具有偶数元素的列表。。。
head = [1,2,3,4,5,6]
mutate_linked_list(head)
[1, 6, 2, 5, 3, 4]