根据栈的性质:先进后出。我们可以用它来实现一些需要前后比较的情况。
题型一:

回文链表

image.png
思路:先把链表遍历一遍,把数据都压入栈。然后再把数据一个个出栈与链表从头开始比较。全部相同则说明是回文链表。

题型二:

有效的括号

image.png
思路:利用栈先进后出的特性来判断是否以正确的顺序闭合

  1. var isValid = function(s) {
  2. const n = s.length;
  3. if (n % 2 === 1) {
  4. return false;
  5. }
  6. const pairs = new Map([
  7. [')', '('],
  8. [']', '['],
  9. ['}', '{'] //每个对应的key和value,方便寻找对应的符号
  10. ]);
  11. const stk = [];
  12. for (let ch of s){
  13. if (pairs.has(ch)) {
  14. if (!stk.length || stk[stk.length - 1] !== pairs.get(ch)) {
  15. return false;
  16. }
  17. stk.pop();
  18. }
  19. else {
  20. stk.push(ch);
  21. }
  22. };
  23. return !stk.length;
  24. };

题型三:

用栈实现队列

image.png
思路:
队列是FIFO,先进先出,栈是LIFO,后进先出。所以我们设立两个栈,一个用于记录输入,一个用于帮助输出。
当需要输出时,我们将输入栈的内容从前往后压入输出栈,此时输入栈前面变成了输出栈后面的。输出栈后面的就后出,即为实现了先进后出,也就是后进先出。

  1. var MyQueue = function() {
  2. this.inStock = [];
  3. this.outStock = [];
  4. };
  5. /**
  6. * @param {number} x
  7. * @return {void}
  8. */
  9. MyQueue.prototype.push = function(x) {
  10. this.inStock.push(x);
  11. };
  12. /**
  13. * @return {number}
  14. */
  15. MyQueue.prototype.pop = function() {
  16. if(!this.outStock.length){
  17. this.swap();
  18. }
  19. return this.outStock.pop();
  20. };
  21. /**
  22. * @return {number}
  23. */
  24. MyQueue.prototype.peek = function() {
  25. if(!this.outStock.length){
  26. this.swap();
  27. }
  28. return this.outStock[this.outStock.length-1];
  29. };
  30. /**
  31. * @return {boolean}
  32. */
  33. MyQueue.prototype.empty = function() {
  34. return !this.inStock.length && !this.outStock.length;
  35. };
  36. MyQueue.prototype.swap = function() {
  37. while(this.inStock.length){
  38. this.outStock.push(this.inStock.pop());
  39. }
  40. }