Skip to content

Commit 4b2650a

Browse files
committed
Remove Linked List Elements
1 parent 9eae3c2 commit 4b2650a

File tree

2 files changed

+84
-12
lines changed

2 files changed

+84
-12
lines changed
Lines changed: 46 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,46 @@
1+
# 203. Remove Linked List Elements
2+
# Topics: 'Linked List', 'Recursion'
3+
# Given the head of a linked list and an integer val, remove all the nodes of the linked list that has Node.val == val, and return the new head.
4+
5+
# Example 1:
6+
7+
# Input: head = [1,2,6,3,4,5,6], val = 6
8+
# Output: [1,2,3,4,5]
9+
10+
# Example 2:
11+
12+
# Input: head = [], val = 1
13+
# Output: []
14+
15+
# Example 3:
16+
17+
# Input: head = [7,7,7,7], val = 7
18+
# Output: []
19+
20+
# Constraints:
21+
22+
# The number of nodes in the list is in the range [0, 104].
23+
# 1 <= Node.val <= 50
24+
# 0 <= val <= 50
25+
26+
27+
from typing import Optional
28+
29+
class ListNode:
30+
def __init__(self, val=0, next=None):
31+
self.val = val
32+
self.next = next
33+
34+
class Solution:
35+
def removeElements(self, head: Optional[ListNode], val: int) -> Optional[ListNode]:
36+
dummy = ListNode()
37+
cur = head
38+
prev = dummy
39+
while cur:
40+
if cur.val != val:
41+
prev.next = cur
42+
prev = prev.next
43+
else:
44+
prev.next = None
45+
cur = cur.next
46+
return dummy.next

234.palindrome_linked_list/palindrome.py

Lines changed: 38 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -30,19 +30,45 @@ def __init__(self, val=0, next=None):
3030
self.val = val
3131
self.next = next
3232

33-
# Memory O(n), Time O(n)
33+
# Memory O(1), Time O(n)
3434
class Solution:
35-
def isPalindrome(self, head: Optional[ListNode]) -> bool:
36-
arr = []
35+
def isPalindrome(self, head: Optional[ListNode])->bool:
36+
fast = head
37+
slow = head
38+
while fast and fast.next:
39+
slow = slow.next
40+
fast = fast.next.next
41+
42+
# reverse
43+
prev = None
44+
while slow:
45+
next = slow.next
46+
slow.next = prev
47+
prev = slow
48+
slow = next
49+
3750
cur = head
38-
while cur:
39-
arr.append(cur.val)
51+
while prev:
52+
if prev.val != cur.val:
53+
return False
54+
prev= prev.next
4055
cur = cur.next
4156

42-
L, R = 0, len(arr)-1
43-
while L < R:
44-
if arr[L] != arr[R]:
45-
return False
46-
L+=1
47-
R-=1
48-
return True
57+
return True
58+
59+
# Memory O(n), Time O(n)
60+
# class Solution:
61+
# def isPalindrome(self, head: Optional[ListNode]) -> bool:
62+
# arr = []
63+
# cur = head
64+
# while cur:
65+
# arr.append(cur.val)
66+
# cur = cur.next
67+
68+
# L, R = 0, len(arr)-1
69+
# while L < R:
70+
# if arr[L] != arr[R]:
71+
# return False
72+
# L+=1
73+
# R-=1
74+
# return True

0 commit comments

Comments
 (0)