从尾到头打印链表

2021-02-22  本文已影响0人  年轻人多学点

js如何来实现栈:

/*使用栈stack类的实现*/
function stack() {
    this.dataStore = [];//保存栈内元素,初始化为一个空数组
    this.top = 0;//栈顶位置,初始化为0
    this.push = push;//入栈
    this.pop = pop;//出栈
    this.peek = peek;//查看栈顶元素
    this.clear = clear;//清空栈
    this.length = length;//栈内存放元素的个数
}

function push(element){
    this.dataStore[this.top++] = element;
}

function pop(){
    return this.dataStore[--this.top];
}

function peek(){
    return this.dataStore[this.top-1];
}

function clear(){
    this.top = 0;
}

function length(){
    return this.top;
}

/*测试stack类的实现*/
var s = new stack();
s.push("aa");
s.push("bb");
s.push("cc");
console.log(s.length());//3
console.log(s.peek());//cc
var popped = s.pop();
console.log(popped);//cc
console.log(s.peek());//bb
function Stack(){
    this.itemArr=[];
    this.top=0;//初始化栈顶位置为0
}

Stack.prototype={
    push:function(el){
        return this.itemArr[this.top++]=el;
    },
    pop:function(){
        return this.itemArr.splice(--this.top,1)
    },
    peek:function(){
        return this.itemArr[this.top-1];
    },
    size:function(){
        return this.top;
    },
    clear:function(){
        this.top=0;
        this.itemArr=[];
        return this.itemArr;
    }
}
var arr=new Stack();

来看看力扣上的面试题吧
输入一个链表的头节点,从尾到头反过来返回每个节点的值(用数组返回)。

示例 1:
输入:head = [1,3,2]
输出:[2,3,1]

限制:

0 <= 链表长度 <= 10000

本道题两种思路,一个是当做栈处理,一个利用js数组当作栈的特性,有如下几种方法:

1.js栈-数组-逆向push

function Stack() {
      // 栈中的属性
      this.items = [];
      // 栈的相关操作
      // push方法 -- 添加一个元素到栈顶位置
      Stack.prototype.push = function (element) {
        this.items.push(element);
      };
      // pop方法 -- 移除栈顶元素,同时返回被移除元素
      Stack.prototype.pop = function () {
        return this.items.pop();
      };
       // size():返回栈的元素个数
      Stack.prototype.size = function () {
        return this.items.length
      }
    }
    var reversePrint = function (head) {
      let stack = new Stack()
      let arr = [];
      while(head) {
        stack.push(head.val)
        head = head.next
      }
      let len = stack.size()
      for (let i = 0; i < len; i++) {
        arr.push(stack.pop());
      }
      return arr;
    };

2.利用js数组当做栈的原理

var reversePrint = function(head) {
    const stack = [];
    let node = head;
    while (node) {
        stack.push(node.val);
        node = node.next;
    }
    return stack.reverse();
};

3.递归反转链表

function reverseLink(head) {
    if (head === null || head.next === null) return head
    const p = reverseLink(head.next)
    head.next.next = head // 指针反转
    head.next = null
    return p // 返回真正的表头
}

4.反转链表

// 首先将链表反转
function reverseLink(head) {
    if (head === null || head.next === null) return head
    let p = head.next
    head.next = null
    let tmp = null
    while (p !== null) {
        tmp = p.next // tmp 指针前进(保存下一个指针信息)
        p.next = head // 指针反转
        head = p // head 指针前进
        p = tmp // p 指针前进
    }
    return head
}

加油!

上一篇 下一篇

猜你喜欢

热点阅读