Skip to content

Commit 259df76

Browse files
authored
Merge pull request #141 from WazedKhan/phase-02-linked-list
Phase-02: Linked-List
2 parents e153484 + e1c7e23 commit 259df76

1 file changed

Lines changed: 103 additions & 0 deletions

File tree

prep/practice/linked_list.py

Lines changed: 103 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,103 @@
1+
from typing import Optional
2+
3+
4+
class ListNode:
5+
def __init__(self, val=0, next=None):
6+
self.val = val
7+
self.next = next
8+
9+
10+
def print_list(head):
11+
current = head
12+
while current is not None:
13+
print(current.val, end=" ")
14+
current = current.next
15+
print()
16+
17+
18+
class Solution:
19+
def reverseList(self, head: Optional[ListNode]) -> Optional[ListNode]:
20+
prev = None
21+
current = head
22+
23+
while current:
24+
next_node = current.next
25+
current.next = prev
26+
prev = current
27+
current = next_node
28+
return prev
29+
30+
def mergeTwoLists(self, list1: Optional[ListNode], list2: Optional[ListNode]) -> Optional[ListNode]:
31+
dummy = ListNode()
32+
tail = dummy
33+
34+
while list1 and list2:
35+
if list1.val < list2.val:
36+
tail.next = list1
37+
list1 = list1.next
38+
else:
39+
tail.next = list2
40+
list2 = list2.next
41+
tail = tail.next
42+
43+
if list1:
44+
tail.next = list1
45+
else:
46+
tail.next = list2
47+
48+
return dummy.next
49+
50+
def hasCycle(self, head: Optional[ListNode]) -> bool:
51+
tortoise, hare = head, head
52+
53+
while hare and hare.next:
54+
tortoise = tortoise.next
55+
hare = hare.next.next
56+
if tortoise == hare:
57+
return True
58+
59+
return False
60+
61+
def list_len(self, head: Optional[ListNode]) -> int:
62+
current = head
63+
count = 0
64+
while current:
65+
count += 1
66+
current = current.next
67+
return count
68+
69+
def removeNthFromEnd(self, head: Optional[ListNode], n: int) -> Optional[ListNode]:
70+
pos = self.list_len(head) - n
71+
dummy = ListNode(0)
72+
dummy.next = head
73+
current = dummy
74+
75+
for _ in range(pos):
76+
current = current.next
77+
current.next = current.next.next
78+
return dummy.next
79+
80+
def reorderList(self, head: Optional[ListNode]) -> None:
81+
slow, fast = head, head
82+
83+
while fast and fast.next:
84+
slow = slow.next
85+
fast = fast.next.next
86+
half = slow.next
87+
slow.next = None
88+
89+
prev = None
90+
while half:
91+
next_node = half.next
92+
half.next = prev
93+
prev = half
94+
half = next_node
95+
96+
while head and prev:
97+
nxt_head = head.next
98+
head.next = prev
99+
nxt_prev = prev.next
100+
prev.next = nxt_head
101+
102+
head = nxt_head
103+
prev = nxt_prev

0 commit comments

Comments
 (0)