9.23栈的链式和数组实现


//栈的链表实现
import java.util.Iterator;
public class Main {
public static void main(String[] args) {
LinkedListStack<Integer> l = new LinkedListStack<>(5);
l.push(1);
l.push(2);
l.push(3);
Iterator<Integer> i = l.iterator();
while (i.hasNext()) {
System.out.print(i.next() + " ");
}
System.out.println();
System.out.println(l.peek());
l.pop();
l.query();
}

public static class LinkedListStack<E> {
private int capacity;//设置的最大容量
private int size;//实际大小
private Node<E> head = new Node<>(null, null);

public LinkedListStack(int capacity) {
this.capacity = capacity;
}

public boolean push(E value) {
if (full()) {
return false;
}
head.next = new Node<>(value, head.next);
size++;
return true;
}

public E pop() {
if (isEmpty()) {
return null;
}
Node<E> p = head.next;
head.next = p.next;
size--;
return p.value;
}

public E peek() {//查栈顶元素
if (isEmpty()) {
return null;
}
Node<E> p = head.next;
return p.value;
}

public boolean isEmpty() {
return size == 0;
}

public boolean full() {
return size == capacity;
}

public void query() {
for (int i = 0; i < size; i++) {
System.out.print(head.next.value + " ");
head = head.next;
}
System.out.println();
}

public Iterator<E> iterator() {//重写迭代器
return new Iterator<E>() {
Node<E> p = head.next;

public boolean hasNext() {
return p != null;
}

public E next() {
E value = p.value;
p = p.next;
return value;
}
};
}

static class Node<E> {
E value;
Node<E> next;

public Node(E value, Node<E> next) {
this.value = value;
this.next = next;
}
}
}
}
 
//栈的数组实现
import java.util.Iterator;
public class Main {
public static void main(String[] args) {
ArrayStack<Integer> l = new ArrayStack<>(5);
l.push(1);
l.push(2);
l.push(3);
Iterator<Integer> i = l.iterator();
while (i.hasNext()) {
System.out.print(i.next() + " ");
}
System.out.println();
System.out.println(l.peek());
l.pop();
l.query();
}

public static class ArrayStack<E> {
private E[] array;
private int top;//数据个数

public ArrayStack(int capacity) {
this.array = (E[]) new Object[capacity];
}

public boolean push(E value) {
if (full()) {
return false;
}
array[top]=value;
top++;
//array[top++]=value; //后加加
return true;
}

public E pop() {
if (isEmpty()) {
return null;
}
E value=array[top-1];
top--;//遍历不到即可
// E value=array[--top];
return value;
}

public E peek() {//查栈顶元素
if (isEmpty()) {
return null;
}
return array[top-1];
}

public boolean isEmpty() {
return top == 0;
}

public boolean full() {
return top== array.length;
}

public void query() {
for (int i = top-1; i >=0; i--) {
System.out.print(array[i]+ " ");
}
System.out.println();
}

public Iterator<E> iterator() {
return new Iterator<E>() {
int p=top;
public boolean hasNext() {
return p>0;
}

public E next() {
E value = array[p-1];
p--;
// E value = array[--p];
return value;
}
};
}

static class Node<E> {
E value;
}
}
}
posted @ 2023-09-23 20:02  赵千万  阅读(6)  评论(0编辑  收藏  举报