-
Notifications
You must be signed in to change notification settings - Fork 1
/
206.ReverseLinkedList.py
executable file
·86 lines (64 loc) · 1.71 KB
/
206.ReverseLinkedList.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Mon Aug 10 20:04:14 2020
@author: nenad
"""
"""
Problem URL: https://leetcode.com/problems/reverse-linked-list/
Problem description:
Reverse a singly linked list.
Example:
Input: 1->2->3->4->5->NULL
Output: 5->4->3->2->1->NULL
Follow up:
A linked list can be reversed either iteratively or recursively. Could you implement both?
"""
# Definition for singly-linked list.
class ListNode:
def __init__(self, val=0, next=None):
self.val = val
self.next = next
class Solution:
def reverseList(self, head: ListNode) -> ListNode:
if head is None:
return head
node = head
prev = None
while True:
next = node.next
node.next = prev
prev = node
if not next:
break
node = next
return node
def reverseList(self, head: ListNode) -> ListNode:
if head is None:
return head
def reverse(node, prev):
next = node.next
node.next = prev
if not next:
return node
return reverse(next, node)
return reverse(head, None)
def reverseList(self, head: ListNode, prev=None) -> ListNode:
if not head:
return prev
nextNode = head.next
head.next = prev
return self.reverseList(nextNode, head)
def printList(node):
while node:
print(node.val, end= " ")
node = node.next
print()
sol = Solution()
n1 = ListNode(1)
n2 = ListNode(2)
n3 = ListNode(3)
n1.next = n2
n2.next = n3
head = sol.reverseList(n1)
printList(head)