这里我的问题是我有一个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
但它没有用......
答案 0 :(得分:2)
[head[0]]+[head[-1]] + head[1:-1]
答案 1 :(得分:0)
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
答案 2 :(得分:0)
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而不是产生价值。
答案 3 :(得分:0)
就像练习......
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)
答案 4 :(得分:0)
怎么样:
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]