Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import org.w3c.dom.Node;
- public class Stack<T> {
- private Node head;
- private int count;
- private Node tail;
- //Retorna cantidad de elementos de la lista
- public int getCount() {
- return this.count;
- }
- public Stack() {
- this.head = null;
- this.count = 0;
- this.tail = null;
- }
- //agreg al principio
- public void AddFirst(T item) {
- Node temp = new Node(item, this.head);
- if(this.count==0) {
- this.tail=temp;
- }
- this.head=temp;
- ++this.count;
- }
- //agrega al final
- public void AddLast(T item) {
- Node temp=new Node(item,null);
- if(this.count==0) {
- this.head=temp;
- }else {
- this.tail.next=temp;
- }
- this.tail=temp;
- ++this.count;
- }
- //exttrae y devuelve el primer elemento
- public T RemoveFirst() {
- if(this.count==0) {
- throw new RuntimeException("La lista esta vacia...");
- }
- T item =this.head.item;
- this.head=this.head.next;
- if(this.head==null) {
- this.tail=null;
- }
- --this.count;
- return item;
- }
- //extrae y devuelve el ultimo elemntoo de la lista
- public T RemoveLast() {
- if(this.count==0) {
- throw new RuntimeException("La lista esta vacia...");
- }
- T item = this.tail.item;
- if(this.head.next==null) {
- this.head=this.tail=null;
- }else {
- Node skip=this.head;
- for(;skip.next.next != null;skip=skip.next) { }
- this.tail=skip;
- this.tail.next=null;
- }
- --this.count;
- return item;
- }
- public void Mostrar() {
- for (Node skip=this.head;skip != null;skip=skip.next) {
- System.out.printf("%s", skip.toString());
- }
- }
- private class Node{
- public T item;
- public Node next;
- public Node() {
- this(null,null);
- }
- public Node(T item) {
- this(item,null);
- }
- public Node(T item,Node next) {
- this.item=item;
- this.next=next;
- }
- public String toString() {
- return this.item.toString();
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment