在linkedlist的开头和结尾插入值的Python函数没有修改linkedlist

2024-10-02 08:14:53 发布

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

This is the question I'm stuck at!

问题是代码没有生成任何输出。(它不打印任何内容。)

我猜LinkedList根本没有被修改

我只定义了两个函数insertAtBeginning(head,x)insertAtEnd(head,x)。其余代码来自Geeksforgeks

class Node:
    def __init__(self,data):
        self.data=data
        self.next=None

# function inserts data x in front of list and returns new head 
def insertAtBegining(head,x):
    # code here
    global a
    if head is None:
        a.head = Node(x)
        # head.next = None
    else:
        node = Node(x)
        node.next = a.head
        a.head = node
        # head.next = node
        
    
# function appends data x at the end of list and returns new head
def insertAtEnd(head,x):
    # code here
    global a
    if head is None:
        a.head = Node(x)
        # head.next = None
    else:
        node = Node(x)
        current = head
        while current.next is not None:
            current = current.next
            
        current.next = node
        # node.next = None

#{ 
#  Driver Code Starts
class Node:
    def __init__(self,data):
        self.data=data
        self.next=None

class LinkedList:
    def __init__(self):
        self.head=None

def printList(head):
    while head:
        print(head.data,end=' ')
        head=head.next
    print()

if __name__ == '__main__':
    t=int(input())
    for cases in range(t):
        n=int(input())
        a=LinkedList()
        
        nodes_info=list(map(int,input().split()))
        for i in range(0,len(nodes_info)-1,2):
            if(nodes_info[i+1]==0):
                a.head = insertAtBegining(a.head,nodes_info[i])
            else:
                a.head = insertAtEnd(a.head,nodes_info[i])
        printList(a.head)

 
# } Driver Code Ends

我希望我已经提供了所有必要的信息。请帮忙


Tags: selfinfononenodedataifisdef

热门问题