fork(12) download
  1. import java.util.*;
  2.  
  3. class ListNode{ // structure of one SLL Node
  4. int val;
  5. ListNode next;
  6. // Constructor - method - create/instantiate objects - alloc memory and init all members
  7. public ListNode(int v){
  8. val = v; next = null;
  9. }
  10. }
  11.  
  12.  
  13.  
  14. class Main{
  15. static Scanner sc = new Scanner(System.in);
  16. public static void main(String[] args){
  17. Solution sol = new Solution();
  18. ListNode h = null; // head of LL (empty)
  19. int n = sc.nextInt();
  20. while(n-->0){
  21. int x = sc.nextInt();
  22. h = sol.insertAtBegin(h, x);
  23. }
  24. sol.printLL(h);
  25. System.out.println();
  26. int findPrev = sc.nextInt();
  27. ListNode ans = sol.findPrevOf(h, findPrev);
  28. if(ans == null)
  29. System.out.println("null");
  30. else
  31. System.out.println(ans.val);
  32. }
  33. }
  34.  
  35. class Solution {
  36. // params - where to insert, what to insert
  37. // returns - new head after insertion
  38. ListNode insertAtBegin(ListNode h, int x){
  39. ListNode nn = new ListNode(x); // new node
  40. nn.next = h;
  41. return nn; // new head
  42. }
  43.  
  44. void printLL(ListNode h){
  45. ListNode t = h;
  46. while(t != null){
  47. System.out.print(t.val + " ");
  48. t = t.next;
  49. }
  50. }
  51.  
  52. int countX(ListNode h, int x){
  53. ListNode t = h;
  54. int c = 0;
  55. while(t != null){
  56. if(t.val == x)
  57. c++;
  58. t = t.next;
  59. }
  60. return c;
  61. }
  62. // sum of elems
  63.  
  64. // max/min val
  65.  
  66. ListNode find(ListNode h, int x){
  67. ListNode t = h;
  68. while(t != null){
  69. if(t.val == x)
  70. return t;
  71. t = t.next;
  72. }
  73. return null;
  74. }
  75.  
  76. ListNode findPrevOf(ListNode h, int x){
  77. ListNode p = null, t = h; // prev & temp
  78. while(t != null){
  79. if(t.val == x)
  80. return p;
  81. p = t;
  82. t = t.next;
  83. }
  84. return null;
  85. }
  86. }
  87.  
  88.  
  89.  
  90.  
  91.  
  92.  
Success #stdin #stdout 0.16s 41768KB
stdin
5
5 4 3 2 1
1
stdout
1 2 3 4 5 
null