Skip to content

Instantly share code, notes, and snippets.

@mylons
Created May 2, 2019 23:07
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mylons/43e3f7a09b95d9da54d55b27be429d1d to your computer and use it in GitHub Desktop.
Save mylons/43e3f7a09b95d9da54d55b27be429d1d to your computer and use it in GitHub Desktop.
leetcodes
# Definition for singly-linked list.
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
class Solution:
def reverseList(self, head: ListNode) -> ListNode:
if head is None or head.next is None:
return head
stack = to_stack(head)
head = ListNode(stack.pop())
cur = head
while stack:
cur.next = ListNode(stack.pop())
cur = cur.next
return head
def to_stack(head: ListNode):
stack = []
cur = head
while cur:
stack.append(cur.val)
cur = cur.next
return stack
import unittest
class TestSolution(unittest.TestCase):
def test_reverse(self):
linked = ListNode(1)
linked.next = ListNode(2)
linked.next.next = ListNode(3)
linked.next.next.next = ListNode(4)
linked.next.next.next.next = ListNode(5)
result = Solution().reverseList(linked)
self.assertEqual(result.val, 5)
self.assertEqual(result.next.val, 4)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment