Posted By

Tiago23 on 11/26/17


Tagged


Versions (?)

LinkedList


 / Published in: Java
 

Linked List Based on the sample provided by CodeFights

  1. class ListNode<T> {
  2. ListNode(T x) {
  3. value = x;
  4. }
  5. T value;
  6. ListNode<T> next;
  7. }
  8.  
  9. static ListNode<Integer> removeKFromList(ListNode<Integer> l, int k) {
  10.  
  11. ListNode<Integer> arr = new ListNode<Integer>(null);
  12.  
  13. while(l != null)
  14. {
  15. if(l.value == k)
  16. {
  17. if(l.next != null)
  18. {
  19. l.value = l.next.value;
  20. if(l.next.next != null)
  21. {
  22. l.next = l.next.next;
  23. }
  24. else
  25. {
  26. l.next = null;
  27. }
  28. }else{
  29. l.value = null;
  30. }
  31. }
  32.  
  33. addNode(arr, l.value);
  34.  
  35. l = l.next;
  36.  
  37. }
  38.  
  39. return arr;
  40.  
  41. }
  42.  
  43. static void addNode(ListNode<Integer> l, int i)
  44. {
  45. if(l.value == null)
  46. {
  47. l.value = i;
  48. }
  49. else
  50. {
  51. if(l.next == null)
  52. {
  53. l.next = new ListNode(i);
  54. }
  55. else
  56. {
  57. ListNode temp = l;
  58. int listIndex = 0;
  59. while(temp != null)
  60. {
  61. temp = temp.next;
  62. listIndex++;
  63. }
  64. temp = new ListNode(i);
  65.  
  66. ListNode x = l;
  67. for (int j = 0; j < listIndex-1; j++)
  68. {
  69. x = x.next;
  70. }
  71. x.next = temp;
  72. }
  73. }
  74. }

Report this snippet  

You need to login to post a comment.