Advertisement
Guest User

Untitled

a guest
Jan 19th, 2018
95
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.40 KB | None | 0 0
  1. public class SingLList {
  2.  
  3. private Node head;
  4.  
  5. private static class Node {
  6. public int data;
  7. public Node next;
  8. }
  9.  
  10. public static void main(String[] args) {
  11. int[] arr = {1,2,3,4,5,6,7};
  12. SingLList list = SingLList.arrayToList(arr);
  13. list.showList();
  14. System.out.println();
  15. list.addBack(8);
  16. // list.removeOdd();
  17. // list.showList();
  18. // list.addFront(1);
  19. // System.out.println();
  20.  
  21. list.showList();
  22. // System.out.println("contains 3? "+list.contains(3));
  23. // System.out.println("contains 8? "+list.contains(8));
  24. // list.clear();
  25. // list.showList();
  26. }
  27.  
  28. public boolean empty() {
  29. return this.head == null;
  30. }
  31.  
  32. public void addFront(int d) {
  33. if ( this.head.data == 0) {
  34. this.head.data = d;
  35. this.head.next = null;
  36. }
  37. else {
  38. SingLList list = new SingLList();
  39. list.head = new Node();
  40. list.head.data = d;
  41. list.head.next = this.head;
  42. this.head = list.head;
  43. }
  44. }
  45. public void addBack(int d) {
  46. if( this.empty() ) {
  47. this.head = new Node();
  48. this.head.data = d;
  49. System.out.print("*");
  50. }
  51. else {
  52. SingLList list = new SingLList();
  53. list.head = this.head.next;
  54. list.addBack(d);
  55.  
  56. }
  57. }
  58. public static SingLList arrayToList(int[] arr) {
  59. SingLList list = new SingLList();
  60. list.head = new Node();
  61. for ( int i = arr.length; i > 0; i-- ) {
  62. list.addFront(arr[i-1]);
  63. }
  64. return list;
  65. }
  66. public void removeOdd() {
  67. SingLList list = new SingLList();
  68. list.head= new Node();
  69. while(! this.empty()) {
  70. if ( this.head.data % 2 == 0) {
  71. list.addFront(this.head.data);
  72. }
  73. this.head = this.head.next;
  74. }
  75.  
  76. this.head = list.head;
  77. }
  78. // public boolean contains(int d)
  79. public void showList() {
  80. SingLList temp = new SingLList();
  81. System.out.print(this.head.data+" ");
  82. if ( this.head.next != null ) {
  83. temp.head = this.head.next;
  84. temp.showList();
  85. }
  86. }
  87. //public void clear()
  88.  
  89. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement