Advertisement
gelita

Remove elements from linked list of integers with value val

Jan 2nd, 2020
189
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.05 KB | None | 0 0
  1. /**
  2. * Remove all elements from a linked list of integers that have value val.
  3. * Definition for singly-linked list.
  4. * public class ListNode {
  5. * int val;
  6. * ListNode next;
  7. * ListNode(int x) { val = x; }
  8. * }
  9. */
  10. class Solution {
  11. public ListNode removeElements(ListNode head, int val) {
  12. ListNode start = new ListNode(0); //create new node
  13. start.next = head; //point new node to the original head
  14. ListNode i = start; //create an iterator node and set it to also point to the head
  15. while(i.next != null){ //while there is another node following
  16. if(i.next.val == val){ //if the val to find is equal to the NEXT node's value
  17. ListNode temp = i.next; //set the node to be removed into the holder node
  18. i.next = temp.next; //move the holder's NEXT node into the iterator node
  19. }else{
  20. i = i.next;
  21. }
  22. }
  23. return start.next;
  24. }
  25. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement