#6 Daily Problems -RemoveKFromList
Hi friends, This is my 6th day of solving one problem per day. I have started to solve the linked list related problems. Actually it is very interesting and fun to solve this type of problems.
Problem:
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.
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 beremoveKFromList(l, k) = [1, 2, 4, 5]
; - For
l = [1, 2, 3, 4, 5, 6, 7]
andk = 10
, the output should beremoveKFromList(l, k) = [1, 2, 3, 4, 5, 6, 7]
.
Input/Output
- [execution time limit] 3 seconds (java)
- [input] linkedlist.integer l
- A singly linked list of integers.
- Guaranteed constraints:
0 ≤ list size ≤ 105
,-1000 ≤ element value ≤ 1000
. - [input] integer k
- An integer.
- Guaranteed constraints:
-1000 ≤ k ≤ 1000
. - [output] linkedlist.integer
- Return
l
with all the values equal tok
removed.
My solution:
// Singly-linked lists are already defined with this interface:// class ListNode<T> {// ListNode(T x) {// value = x;// }// T value;// ListNode<T> next;// }//public ListNode<Integer> removeKFromList(ListNode<Integer> l, int k) {
ListNode temp = l;
// if give linked list is empty then return
if (l == null){
return l;
}
// iterate until given starting value are matching
while(l.value == k ){
l = l.next;
if (l == null)
return l; // return, after the matching values and removed the remains are null
}
// check the next values are matching if matched then remove the elements from the linked list
while(temp.next != null){
if (temp.next.value.equals(k)){
temp.next = temp.next.next;
}else{
temp=temp.next;
}
}
return l;
}
Ok friends, please help me to improve this solution ad help me to learn somethings from you. Thanks. lets meet tomorrow.
Happy coding!
Buy me a coffee?
If you like this article, you can buy me a coffee. Thanks!