Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- class SinglyLinkedList{
- private Node head; //nó cabeça, front da lista
- public SinglyLinkedList(){ //construtor inicializado como nulo
- head = null;
- }
- public void insertHead(int x){
- Node newNode = new Node(x); //Create a new link with a value attached to it
- newNode.next = head; //Set the new link to point to the current head
- head = newNode; //Now set the new link to be the head
- }
- /**
- * Inserts a new node at a specified position
- * @param head head node of the linked list
- * @param data data to be stored in a new node
- * @param position position at which a new node is to be inserted
- * @return reference of the head of the linked list
- */
- Node InsertNth(Node head, int data, int position) {
- Node newNode = new Node();
- newNode.data = data;
- if (position == 0) {
- newNode.next = head;
- return newNode;
- }
- Node current = head;
- while (--position > 0) {
- current = current.next;
- }
- newNode.next = current.next;
- current.next = newNode;
- return head;
- }
- public Node deleteHead(){
- Node temp = head;
- head = head.next; //Make the second element in the list the new head, the Java garbage collector will later remove the old head
- return temp; //retorna o elemento deletado
- }
- public boolean isEmpty(){ // retorna true se a lista estiver vazia
- return(head == null);
- }
- public void display(){ //printa o conteúdo da lista
- Node current = head;
- while(current!=null){
- System.out.print(current.getValue()+" ");
- current = current.next;
- }
- System.out.println();
- }
- public static void main(String args[]){
- SinglyLinkedList myList = new SinglyLinkedList();
- System.out.println(myList.isEmpty()); //Will print true
- myList.insertHead(5);
- myList.insertHead(7);
- myList.insertHead(10);
- myList.display(); // 10(head) --> 7 --> 5
- myList.deleteHead();
- myList.display(); // 7(head) --> 5
- }
- }
- class Node{
- public int value;//valor do nó
- public Node next; //ponteiro para o próximo nó
- /**
- * Constructor
- *
- * @param valuein Value to be put in the node
- */
- public Node(int valuein){
- value = valuein;
- }
- public int getValue(){ //método: retorna o valor do nó
- return value;
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement