Created
May 2, 2019 23:07
-
-
Save mylons/43e3f7a09b95d9da54d55b27be429d1d to your computer and use it in GitHub Desktop.
leetcodes
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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