Advertisement
ramomjcs

Lista Simplesmente Encadeada

Mar 13th, 2019
88
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.38 KB | None | 0 0
  1. class SinglyLinkedList{
  2.  
  3. private Node head; //nó cabeça, front da lista
  4.  
  5. public SinglyLinkedList(){ //construtor inicializado como nulo
  6. head = null;
  7. }
  8.  
  9. public void insertHead(int x){
  10. Node newNode = new Node(x); //Create a new link with a value attached to it
  11. newNode.next = head; //Set the new link to point to the current head
  12. head = newNode; //Now set the new link to be the head
  13. }
  14.  
  15.  
  16. /**
  17. * Inserts a new node at a specified position
  18. * @param head head node of the linked list
  19. * @param data data to be stored in a new node
  20. * @param position position at which a new node is to be inserted
  21. * @return reference of the head of the linked list
  22. */
  23.  
  24. Node InsertNth(Node head, int data, int position) {
  25.  
  26. Node newNode = new Node();
  27. newNode.data = data;
  28.  
  29. if (position == 0) {
  30. newNode.next = head;
  31. return newNode;
  32. }
  33.  
  34. Node current = head;
  35.  
  36. while (--position > 0) {
  37. current = current.next;
  38. }
  39.  
  40. newNode.next = current.next;
  41. current.next = newNode;
  42. return head;
  43. }
  44.  
  45. public Node deleteHead(){
  46. Node temp = head;
  47. head = head.next; //Make the second element in the list the new head, the Java garbage collector will later remove the old head
  48. return temp; //retorna o elemento deletado
  49. }
  50.  
  51.  
  52. public boolean isEmpty(){ // retorna true se a lista estiver vazia
  53. return(head == null);
  54. }
  55.  
  56. public void display(){ //printa o conteúdo da lista
  57. Node current = head;
  58. while(current!=null){
  59. System.out.print(current.getValue()+" ");
  60. current = current.next;
  61. }
  62. System.out.println();
  63. }
  64.  
  65.  
  66. public static void main(String args[]){
  67. SinglyLinkedList myList = new SinglyLinkedList();
  68.  
  69. System.out.println(myList.isEmpty()); //Will print true
  70.  
  71. myList.insertHead(5);
  72. myList.insertHead(7);
  73. myList.insertHead(10);
  74.  
  75. myList.display(); // 10(head) --> 7 --> 5
  76.  
  77. myList.deleteHead();
  78.  
  79. myList.display(); // 7(head) --> 5
  80. }
  81. }
  82.  
  83. class Node{
  84.  
  85. public int value;//valor do nó
  86.  
  87. public Node next; //ponteiro para o próximo nó
  88.  
  89. /**
  90. * Constructor
  91. *
  92. * @param valuein Value to be put in the node
  93. */
  94. public Node(int valuein){
  95. value = valuein;
  96. }
  97.  
  98. public int getValue(){ //método: retorna o valor do nó
  99. return value;
  100. }
  101.  
  102. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement