I'm trying to write a reversed linked list on leet code and I keep getting a `Syntax error on line 37: print(curr.data, end=" ") I don't get what the problem is. my code is running just fine on vs code. does anyone know what to do?
class Node:
def __init__(self, data):
self.data = data
self.next = None
def create_linked_list():
nums = input("Enter numbers (space-separated): ").split()
if not nums:
return None
head = Node(int(nums[0]))
curr = head
for num in nums[1:]:
new_node = Node(int(num))
curr.next = new_node
curr = curr.next
return head
def reverse_linked_list(head):
prev = None
curr = head
while curr:
next_node = curr.next
curr.next = prev
prev = curr
curr = next_node
return prev
def display_linked_list(head):
curr = head
while curr:
print(curr.data, end=" ")
curr = curr.next
print()
head = create_linked_list()
print("Original linked list:")
display_linked_list(head)
head = reverse_linked_list(head)
print("Reversed linked list:")
display_linked_list(head)
You would get this syntax error if you posted your code having selected "Python" as language (which is backed by a Python 2.7 compiler), instead of "Python3".
The syntax print(curr.data, end=" ")
is not compatible with Python 2, where print
is not a function, but a statement. To do the same in Python 2, you would do:
print curr.val,
(Note that LeetCode defines a ListNode
class with a val
attribute, not data
).
In short, don't choose "Python" in the LeetCode UI, but "Python3".