假设 head 不为空,下面是实现单向循环链表在头节点后插入新节点的代码,横线处应填入( )。 class Node: def __init__(self, val): self.val = val self.next = None def insert_after_head(head, x): new_node = Node(x) # ---------------------------
A:new_node.next = head.next head.next = new_node
B:new_node.next = head head.next = new_node
C:head.next = new_node new_node.next = head
D:new_node.next = head.next; head = new_node
正确答案:A
答案解析
创建新节点后,需将其指针指向头节点的下一个节点,以保持原链表连接不断开;随后将头节点的指针更新为指向新节点,使新节点插入到头节点之后。此过程不涉及修改头节点本身,仅修改指针的指向关系。操作中不能使任何原有节点脱离链表,也不能使头节点失去对后续节点的引用。整个插入过程仅通过调整两个指针实现:新节点的next和头节点的next。
试卷来源:202606 CCF-GESP编程能力等级认证Python五级真题