普通链表,代码参考自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; } } } }