以python开头和结尾的链表

2024-04-28 16:19:13 发布

您现在位置:Python中文网/ 问答频道 /正文

我的问题是我有一个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

但它不起作用。。。。你知道吗


Tags: gtnode概念节点defheadlistnext
3条回答
[head[0]]+[head[-1]] + head[1:-1]
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)

很明显,你可以做一个列表,并附加到它,而不是产生值。你知道吗

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

相关问题 更多 >