题目描述
输入一个链表,按链表值从尾到头的顺序返回一个ArrayList。
分析
要了解链表的数据结构:
val属性存储当前的值,next属性存储下一个节点的引用。
要遍历链表就是不断找到当前节点的next节点,当next节点是null时,说明是最后一个节点,停止遍历。
最后别忘了,从尾到头遍历链表,不要忘了将你的结果进行翻转。
代码
/*function ListNode(x){ this.val = x; this.next = null;}*/function printListFromTailToHead(head){ const result = []; let temp = head; while(temp){ result.push(temp.val); temp = temp.next; } return result.reverse();}
拓展
链表定义:用一组任意存储的单元来存储线性表的数据元素。
一个对象存储着本身的值和下一个元素的地址。
需要遍历才能查询到元素,查询慢。
插入元素只需断开连接重新赋值,插入快。
function LinkList(){ function node(element){ this.value = element; this.next = null; } let length = 0; let head = null; } LinkList.prototype = { // 追加 append:function(element){ var node = new node(element); var temp = this.head; if(this.head){ //遍历找到链表的终点 while(temp.next){ temp = temp.next; } temp.next = node; }else{ this.head = node; } this.length++; }, // 插入 insert:function(element,index){ if(index <= this.length && index>0){ var node = new node(element); var currentIndex = 0; var currentNode = this.head; var preNode = null; if (currentIndex === 0) { node.next = currentNode; this.head = node; return; } while(currentIndex
链表翻转
把初始链表头当做基准点
移动下一个元素到头部
直到下一个元素为空
/** * Definition for singly-linked list. * function ListNode(val) { * this.val = val; * this.next = null; * } */ /** * @param {ListNode} head * @return {ListNode} */ var reverseList = function (head) { let currentNode = null; let headNode = head; while (head && head.next) { // 将当前节点从链表中取出 currentNode = head.next; head.next = currentNode.next; // 将取出的节点移动到头部 currentNode.next = headNode; headNode = currentNode; } return headNode; };