JavaScript链表
Posted chenss15060100790
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了JavaScript链表相关的知识,希望对你有一定的参考价值。
普通链表,代码参考自Java,按需自行调整
function LinkedList(s) var size = s||5, cnt = 0; var first, last; return add: function (v) var e = value: v, pre:last; if(cnt === 0)last = first = e; cnt ++; else if(cnt === size)first = first.next; last.next = e; last = e; else cnt++; last.next = e; last = e; , lastNode: function() return last; , firstNode: function() return first; , get: function (idx) var v; while(idx --> 0) v = first.next return v.value; , first: function () return first.value; , last: function () return last.value; , peek: function () var res = last; last = last.pre; delete last.next; return res;
扩展了一部分功能,用于做播放器,上一首、下一首、最后一首、第一首这样的功能
/** * 简单的链表 */ function LinkedList(s) var size = s||5, cnt = 0; var first, last, cur; return add: function (v) var e = value: v, pre:last; if(cnt === 0)last = first = e; cnt ++; else if(cnt === size)first = first.next; delete first.pre; last.next = e; last = e; else cnt++; last.next = e; last = e; , lastNode: function() return last; , firstNode: function() return first; , get: function (idx) var n = first; while(idx --> 0) n = n.next return n.value; , set: function (idx, value) var n = first, id = idx; while(id --> 0) n = n.next cnt = idx + 1; n.value = value; last = n; , first: function () cnt = 1; last = first; return first.value; , last: function () while (last.next) last = last.next; cnt++; return last.value; , next: function() if(last.next) cnt++; last = last.next; return last.value; , back: function() if(last.pre) cnt--; last = last.pre; return last.value;
以上是关于JavaScript链表的主要内容,如果未能解决你的问题,请参考以下文章
[JavaScript 刷题] 链表 - 相交链表, leetcode 160
[JavaScript 刷题] 链表 - 相交链表, leetcode 160
[JavaScript 刷题] 链表 - 反转链表, leetcode 206