Java中如何实现栈、队列

1、如何实现栈

  • ArrayDeque:底层基于数组实现,故随机访问元素性能较好
  • LinkedList:底层基于链表实现,故插入、删除操作性能比较好

使用例子:实现一个栈操作,将1-12月的英文单词压入栈,然后再将其取出

import java.util.*;

//如何实现栈、队列

public class Stacks {
	static String[] months = {"January","February","March","April","May","June","July","August",
			"September","October","November","December"};
	
public static void main(String[] args) {
   //ArrayDeque可以当做栈、队列使用,底层是数组实现,所以随机访问元素性能比较好
   ArrayDeque stack = new ArrayDeque();
   for(int i = 0; i < months.length; i++) {
	stack.push(months[i] + " ");
   }
   while(!stack.isEmpty()) {
	System.out.print(stack.pop());
  }
  System.out.println();
		
//LinkedList既可以做栈,又可以做队列使用,底层基于链表实现,故插入、删除性能比较好
  LinkedList stk = new LinkedList();
  for(int i = 0;i < months.length; i++) {
        stk.push(months[i] + " ");
  }
		
  while(!stk.isEmpty()) {
	System.out.print(stk.pop());
  }
  System.out.println();
		
  }
}
  • 栈常用方法:

isEmpty():栈空返回真,否则返回假

peek():返回栈顶元素,但不出栈

push():入栈

pop():出栈

 

2、如何实现队列

  • ArrayDeque:底层基于数组实现,故随机访问元素性能较好
  • LinkedList:底层基于链表实现,故插入、删除操作性能比较好

使用例子:实现一个队列操作,将1-12月的英文单词入队,然后再将其取出

import java.util.*;

//实现队列

public class Queues {
	static String[] months = {"January","February","March","April","May","June","July","August",
			"September","October","November","December"};
	
public static void main(String[] args) {
	ArrayDeque queue = new ArrayDeque();
	for(int i = 0; i < months.length; i++)
		queue.offer(months[i] + " ");
		
	while(!queue.isEmpty()) {
		System.out.print(queue.poll());
	}
	System.out.println();
		
	LinkedList que = new LinkedList();
	for(int i = 0; i < months.length; i++)
		que.offer(months[i] + " ");
		
	while(!que.isEmpty()) {
		System.out.print(que.poll());
	}
  }
}

队列常用方法:

  • offer():入队,若入队失败则返回false
  • offerFirst():插入队头
  • offerLast():插入队尾
  • poll():出队,获取并移除队头元素,若为空则返回Null
  • remove():获取并移除队头元素(若队列空则抛出NoSuchElementException异常)

 

你可能感兴趣的:(栈,队列)