I don't understand why these near identical classes with almost the same functions output different things.
They are both supposed to return a reversed array by reading them as linked lists.
The first one outputs the reversed array but the second one outputs the the memory location.
I would like for the second class below to output the reversed array just like the first class does.
# Definition for singly-linked list.
class ListNode:
def __init__(self, val=0, next=None):
self.val = val
self.next = next
class Solution:
def isPalindrome(self, head):
vals = []
while head:
vals += head.val,
head = head.next
return vals[0][::-1]
head = [1,2,3,4,5]
Solution().isPalindrome(ListNode(head))
outputs [5, 4, 3, 2, 1]
# Definition for singly-linked list.
class ListNode:
def __init__(self, val=0, next=None):
self.val = val
self.next = next
class Solution:
def isPalindrome(self, head):
prev = None
while head:
curr = head
head = head.next
curr.next = prev
prev = curr
return prev
head = [1,2,3,4,5]
Solution().isPalindrome(ListNode(head))
outputs <__main__.ListNode at 0x7f49e28afa00>