栈/队列实例

(1)栈的实例:

 我们接下来通过链表的形式来创建栈,方便扩充。

/**
* Stack的特性:后进先出
*/
public class Stack {
public Node head;
public Node current;

public static void main(String[] args) {
Stack stack = new Stack();
stack.push(11);
stack.push(12);
stack.push(13);
System.out.println(stack.pop().data);
System.out.println(stack.pop().data);
System.out.println(stack.pop().data);
}

public void push(int data) {
if (head == null) {
head = new Node(data);
current = head;
} else {
Node node = new Node(data);
node.pre = current;
current = node;

}
}

public Node pop() {
if (current == null) {
return null;
}
Node node = current;
current = node.pre;
return node;
}
}
class Node {
Node pre;
int data;

public Node(int data) {
this.data = data;
}
}

 

import java.util.LinkedList;
import java.util.List;

public class Queue {
public Node1 head;
public Node1 curent;

public void add(int data) {
if (head == null) {
head = new Node1(data);
curent = head;
} else {
curent.next = new Node1(data);
curent = curent.next;
}
}

// 方法:出队操作
public int pop() throws Exception {
if (head == null) {
throw new Exception("队列为空");
}

Node1 node = head; // node结点就是我们要出队的结点
head = head.next; // 出队之后,head指针向下移
return node.data;

}

}

class Node1 {
Node1 next;
int data;

public Node1(int data) {
this.data = data;
}
}

posted @ 2017-05-10 11:23  ding9587  阅读(181)  评论(0编辑  收藏  举报