You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python链表右旋代码运行无输出问题求助

解决Python单链表右旋无输出问题

嘿,我看了你的代码,其实右旋的逻辑完全没问题!你觉得没有输出的原因是——你直接打印了链表节点对象,Python默认只会输出这个对象的内存地址,而不是链表的元素内容,所以看起来像没输出一样。

问题分析

比如你执行print(rotateRight(node1,k)),实际输出的是类似<__main__.likedListNode object at 0x7f9b1c05d190>这样的内容,只是这不是你想要的链表元素展示,所以误以为没有输出。

解决方案

我们需要写一个辅助函数,用来遍历链表并打印每个节点的值,这样就能直观看到右旋后的结果了。

修改后的完整代码

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

def rotateRight(head, k):
    if not head:
        return None
    if not head.next:
        return head
    # close the linked list into the ring
    old_tail = head
    n = 1
    while old_tail.next:
        old_tail = old_tail.next
        n += 1
    old_tail.next = head
    # find new tail : (n - k % n - 1)th node
    # and new head : (n - k % n)th node
    new_tail = head
    for i in range(n - k % n - 1):
        new_tail = new_tail.next
    new_head = new_tail.next
    # break the ring
    new_tail.next = None
    return new_head

# 新增辅助函数:遍历链表并打印所有节点值
def printLinkedList(head):
    current = head
    while current:
        print(current.value, end=" -> ")
        current = current.next
    print("None")  # 标记链表结束

node1=likedListNode("1")
node2=likedListNode("2")
node3=likedListNode("3")
node4=likedListNode("4")
node5=likedListNode("5")
node1.next = node2
node2.next = node3
node3.next = node4
node4.next = node5
k=2

# 调用辅助函数打印右旋后的链表
result_head = rotateRight(node1,k)
printLinkedList(result_head)

运行结果

执行后你会看到预期的右旋结果:

4 -> 5 -> 1 -> 2 -> 3 -> None

另外提个小建议:类名最好遵循Python的大驼峰命名法,比如把likedListNode改成LinkedListNode,这样代码可读性更好哦~

内容的提问来源于stack exchange,提问作者Nilesh Bhawsar

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.06 06:51:49