Reputation: 73
I am solving this problem on leetcode - Reverse linked list
My code is running fine I believe but I am receiving "None" in the output. How can I remove this?
This is how output is coming for the input [1,2,3,4,5]
:
Output:
[5,4,3,2,1,None]
Here is the code I tried:
class Solution:
def reverseList(self, head: ListNode) -> ListNode:
if head is None: return None
if head.next is None: return head
cur = head
prev = ListNode(None)
temp = head.next
while temp:
cur.next = prev
prev = cur
cur = temp
temp = temp.next
if temp is None:
cur.next = prev
head = cur
return head
Upvotes: 1
Views: 201
Reputation: 12972
As a complementary answer, you are using too many useless if statements that you could avoid. Similarly to your answer, your could reduce it simply to the following:
def reverseList(self, head: ListNode) -> ListNode:
prev = None
while head:
temp = head.next
head.next = prev
prev = head
head = temp
return prev
Upvotes: 1
Reputation: 11929
With prev = ListNode(None)
you create a new Node with value = None
and next Node None
.
So, in your example Node 1
does not have None as self.next
, but a Node with None as self.val.
prev = None
should solve the issue.
Upvotes: 1