Skip to content

Commit 16b2bee

Browse files
solves reverse a linked list in python
1 parent de40105 commit 16b2bee

File tree

2 files changed

+22
-1
lines changed

2 files changed

+22
-1
lines changed

README.md

+1-1
Original file line numberDiff line numberDiff line change
@@ -60,7 +60,7 @@
6060
| 203 | [Remove Linked List Elements](https://leetcode.com/problems/remove-linked-list-elements) | Easy | [![Java](https://img.icons8.com/color/40/000000/java-coffee-cup-logo.png)](src/RemoveLinkedListElements.java) [![Python](https://img.icons8.com/color/35/000000/python.png)](python/remove_linked_list_elements.py) |
6161
| 204 | [Count Primes](https://leetcode.com/problems/count-primes) | Easy | [![Java](https://img.icons8.com/color/40/000000/java-coffee-cup-logo.png)](src/CountPrimes.java) [![Python](https://img.icons8.com/color/35/000000/python.png)](python/count_primes.py) |
6262
| 205 | [Isomorphic Strings](https://leetcode.com/problems/isomorphic-strings) | Easy | [![Java](https://img.icons8.com/color/40/000000/java-coffee-cup-logo.png)](src/IsomorphicStrings.java) [![Python](https://img.icons8.com/color/35/000000/python.png)](python/isomorphic_strings.py) |
63-
| 206 | [Reverse Linked Lists](https://leetcode.com/problems/reverse-linked-list) | Easy | [![Java](https://img.icons8.com/color/40/000000/java-coffee-cup-logo.png)](src/ReverseLinkedList.java) |
63+
| 206 | [Reverse Linked Lists](https://leetcode.com/problems/reverse-linked-list) | Easy | [![Java](https://img.icons8.com/color/40/000000/java-coffee-cup-logo.png)](src/ReverseLinkedList.java) [![Python](https://img.icons8.com/color/35/000000/python.png)](python/reverse_linked_list.py) |
6464
| 217 | [Contains Duplicate](https://leetcode.com/problems/contains-duplicate) | Easy | [![Java](https://img.icons8.com/color/40/000000/java-coffee-cup-logo.png)](src/ContainsDuplicate.java) |
6565
| 219 | [Contains Duplicate II](https://leetcode.com/problems/contains-duplicate-ii) | Easy | [![Java](https://img.icons8.com/color/40/000000/java-coffee-cup-logo.png)](src/ContainsDuplicateII.java) |
6666
| 225 | [Implement Stack using Queues](https://leetcode.com/problems/implement-stack-using-queues) | Easy | [![Java](https://img.icons8.com/color/40/000000/java-coffee-cup-logo.png)](src/MyStack.java) |

python/reverse_linked_list.py

+21
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
from typing import Optional
2+
3+
4+
# Definition for singly-linked list.
5+
class ListNode:
6+
def __init__(self, val=0, next=None):
7+
self.val = val
8+
self.next = next
9+
10+
11+
class Solution:
12+
def reverseList(self, head: ListNode) -> Optional[ListNode]:
13+
if head is None or head.next is None:
14+
return head
15+
a, b, c = head, head.next, head.next.next
16+
a.next = None
17+
while c is not None:
18+
b.next = a
19+
a, b, c = b, c, c.next
20+
b.next = a
21+
return b

0 commit comments

Comments
 (0)