Python 函数 --- 在链表的开头和结尾插入一个值 --- 不修改链表
Python function --- to insert a value at start and end of linked-list --- is not modifying the linkedlist
This is the question I'm stuck at!
问题是代码没有生成任何输出。 (它不打印任何东西。)
我猜 LinkedList
根本没有被修改!
我只定义了insertAtBeginning(head,x)
和insertAtEnd(head,x)
这两个函数。其余代码来自 GeeksForGeeks.
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
希望我已经提供了所有必要的信息。请帮忙。
看起来 insertAtBegining
应该 return 链表的新头,而你的实现看起来 return 根本不是。
This is the question I'm stuck at!
问题是代码没有生成任何输出。 (它不打印任何东西。)
我猜 LinkedList
根本没有被修改!
我只定义了insertAtBeginning(head,x)
和insertAtEnd(head,x)
这两个函数。其余代码来自 GeeksForGeeks.
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
希望我已经提供了所有必要的信息。请帮忙。
看起来 insertAtBegining
应该 return 链表的新头,而你的实现看起来 return 根本不是。