跳到主要内容

简述从尾到头输出链表 ?

参考答案:

从尾到头输出链表通常意味着你需要以相反的顺序遍历链表并输出每个节点的值。链表是一种常见的数据结构,其中每个节点包含数据和指向下一个节点的指针。

在Python中,你可以使用递归或迭代的方法来实现从尾到头输出链表。以下是两种方法的示例代码:

递归方法

class ListNode:
    def __init__(self, value=0, next=None):
        self.value = value
        self.next = next

def print_list_from_tail_to_head_recursive(node):
    if node is None:
        return
    print_list_from_tail_to_head_recursive(node.next)
    print(node.value)

# 示例链表:1 -> 2 -> 3 -> 4
head = ListNode(1)
head.next = ListNode(2)
head.next.next = ListNode(3)
head.next.next.next = ListNode(4)

print_list_from_tail_to_head_recursive(head)  # 输出:4 3 2 1

迭代方法

class ListNode:
    def __init__(self, value=0, next=None):
        self.value = value
        self.next = next

def print_list_from_tail_to_head_iterative(head):
    if head is None:
        return
    
    # 使用栈来反转遍历顺序
    stack = []
    current = head
    while current is not None:
        stack.append(current.value)
        current = current.next
    
    # 从栈中弹出元素并打印
    while stack:
        print(stack.pop())

# 示例链表:1 -> 2 -> 3 -> 4
head = ListNode(1)
head.next = ListNode(2)
head.next.next = ListNode(3)
head.next.next.next = ListNode(4)

print_list_from_tail_to_head_iterative(head)  # 输出:4 3 2 1

在上面的代码中,ListNode 类用于表示链表节点。print_list_from_tail_to_head_recursive 函数使用递归方法从尾到头输出链表,而 print_list_from_tail_to_head_iterative 函数使用迭代方法结合栈来实现相同的功能。