Advertisement
Guest User

Untitled

a guest
Dec 5th, 2019
122
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.11 KB | None | 0 0
  1. // ===== Code from file IntNode.java =====
  2. public class IntNode {
  3. private int dataVal;
  4. private IntNode nextNodePtr;
  5.  
  6. public IntNode(int dataInit, IntNode nextLoc) {
  7. this.dataVal = dataInit;
  8. this.nextNodePtr = nextLoc;
  9. }
  10.  
  11. public IntNode(int dataInit) {
  12. this.dataVal = dataInit;
  13. this.nextNodePtr = null;
  14. }
  15.  
  16. /* Insert node after this node.
  17. * Before: this -- next
  18. * After: this -- node -- next
  19. */
  20. public void insertAfter(IntNode nodePtr) {
  21. IntNode tmpNext;
  22.  
  23. tmpNext = this.nextNodePtr; // Remember next
  24. this.nextNodePtr = nodePtr; // this -- node -- ?
  25. nodePtr.nextNodePtr = tmpNext; // this -- node -- next
  26. }
  27.  
  28. // Grab location pointed by nextNodePtr
  29. public IntNode getNext() {
  30. return this.nextNodePtr;
  31. }
  32. public int getDataVal() {
  33. return this.dataVal;
  34. }
  35. }
  36. // ===== end =====
  37.  
  38. // ===== Code from file CustomLinkedList.java =====
  39. import java.util.Random;
  40.  
  41. public class CustomLinkedList {
  42. public static void main (String [] args) {
  43. Random randGen = new Random();
  44. IntNode headObj; // Create intNode objects
  45. IntNode currObj;
  46. IntNode lastObj;
  47. int i; // Loop index
  48. int negativeCntr;
  49.  
  50. negativeCntr = 0;
  51. headObj = new IntNode(-1); // Front of nodes list
  52. lastObj = headObj;
  53.  
  54. for (i = 0; i < 10; ++i) { // Append 10 rand nums
  55. int rand = randGen.nextInt(21) - 10;
  56. currObj = new IntNode(rand);
  57. lastObj.insertAfter(currObj); // Append curr
  58. lastObj = currObj; // Curr is the new last item
  59. }
  60.  
  61. currObj = headObj; // Print the list
  62. while (currObj != null) {
  63. System.out.print(currObj.getDataVal() + ", ");
  64. currObj = currObj.getNext();
  65. }
  66. System.out.println("");
  67.  
  68. currObj = headObj; // Count number of negative numbers
  69. while (currObj != null) {
  70.  
  71. /* Your solution goes here */
  72.  
  73. currObj = currObj.getNext();
  74. }
  75. System.out.println("Number of negatives: " + negativeCntr);
  76. }
  77. }
  78. // ===== end =====
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement