我被问到self.head, self.tail = self.tail, self.head在双链接列表上的作用是什么。
如果我实现了这段代码,列表现在只包含添加的最后一项.
# Represent a node of doubly linked list
class Node:
def __init__(self, data):
self.data = data;
self.previous = None;
self.next = None;
class DoublyLinkedList:
# Represent the head and tail of the doubly linked list
def __init__(self):
self.head = None;
self.tail = None;
# addNode() will add a node to the list
def addNode(self, data):
# Create a new node
newNode = Node(data);
# If list is empty
if (self.head == None):
# Both head and tail will point to newNode
self.head = self.tail = newNode;
# head's previous will point to None
self.head.previous = None;
# tail's next will point to None, as it is the last node of the list
self.tail.next = None;
else:
# newNode will be added after tail such that tail's next will point to newNode
self.tail.next = newNode;
# newNode's previous will point to tail
newNode.previous = self.tail;
# newNode will become new tail
self.tail = newNode;
# As it is last node, tail's next will point to None
self.tail.next = None;
# display() will print out the nodes of the list
def display(self):
# Node current will point to head
current = self.head;
if (self.head == None):
print("List is empty");
return;
print("Nodes of doubly linked list: ");
while (current != None):
# Prints each node by incrementing pointer.
print(current.data),;
current = current.next;
def weird_line(self):
self.head, self.tail = self.tail, self.head
dList = DoublyLinkedList();
# Add nodes to the list
dList.addNode(1);
dList.addNode(2);
dList.addNode(3);
dList.addNode(4);
dList.addNode(5);
dList.weird_line();
dList.display();产出:5
来源:https://www.javatpoint.com/python-program-to-create-and-display-a-doubly-linked-list
然而,我的教授让我从四个选项中选择一个:
G 214
我很确定,我的初步答案是正确的。有没有人会认为他给我的一个可能的答案是正确的?
发布于 2022-05-15 14:23:37
从您介绍的内容来看,您正确地看到,最后的display调用将打印上次添加的节点的值。
这四个选项中没有一个是正确的。
我们还可以说一些其他的话:
head和tail的这个交换将使列表不一致,正如您所期望的那样:
head或head.previous是Nonetail,或者tail.next是非emtpy列表,如果您从head节点开始,并遵循next引用,直到节点的next属性为None,您将结束于tail节点。在非emtpy列表中的tail节点开始,并遵循previous引用,直到节点的previous属性是None,您将结束在head节点.如果在至少有2个节点的列表上调用weird_line,所有这些不变量都将被违反。
https://stackoverflow.com/questions/72248662
复制相似问题