Section titled Problem
Problem
Given a singly linked list of integers l and an integer k, remove all elements from list l that have a value equal to k.
Example
- For
l = [3, 1, 2, 3, 4, 5]andk = 3, the output should besolution(l, k) = [1, 2, 4, 5]; - For
l = [1, 2, 3, 4, 5, 6, 7]andk = 10, the output should besolution(l, k) = [1, 2, 3, 4, 5, 6, 7].
Note: Try to solve this task in O(n) time using O(1) additional space, where n is the number of elements in the list, since this is what you’ll be asked to do during an interview.
Section titled Solution
Solution
- The solution is straight forward, iterate linked list if
cursorvalue equals withkskip cursor value by usingprev.Next=cursor.Next
Talk is cheap, I show you the code. lol
<CH.Section>
- create head that contains
*ListNodeand storeheadon theprev, because we cannot get previous ListNode from current Node - Iterate linked-list using help
cursor - If current
cursorvalue equals withkthen delete current cursor by skipping current node - Otherwise update prev with current cursor
- Return
head.next
// Singly-linked lists are already defined with this interface:
// type ListNode struct {
// Value interface{}
// Next *ListNode
// }
//
func solution(l *ListNode, k int) *ListNode {
head:=&ListNode{Next:l}
prev:= head
for cursor:=l;cursor!=nil;cursor=cursor.Next{
if cursor.Value.(int) == k {
prev.Next = cursor.Next
}else{
prev = cursor
}
}
return head.Next
}</CH.Section>