1+ function LinkedList ( ) {
2+ var Node = function ( element ) { //新元素构造
3+ this . element = element ;
4+ this . next = null ;
5+ } ;
6+ var length = 0 ;
7+ var head = null ;
8+
9+ this . append = function ( element ) {
10+ var node = new Node ( element ) ; //构造新的元素节点
11+ var current ;
12+ if ( head === null ) { //头节点为空时 当前结点作为头节点
13+ head = node ;
14+ } else {
15+ current = head ;
16+ while ( current . next ) { //遍历,直到节点的next为null时停止循环,当前节点为尾节点
17+ current = current . next ;
18+ }
19+ current . next = node ; //将尾节点指向新的元素,新元素作为尾节点
20+ }
21+ length ++ ; //更新链表长度
22+ } ;
23+ this . removeAt = function ( position ) {
24+ if ( position > - 1 && position < length ) {
25+ var current = head ;
26+ var index = 0 ;
27+ var previous ;
28+ if ( position == 0 ) {
29+ head = current . next ;
30+ } else {
31+ while ( index ++ < position ) {
32+ previous = current ;
33+ current = current . next ;
34+ }
35+ previous . next = current . next ;
36+ }
37+ length -- ;
38+ return current . element ;
39+ } else {
40+ return null ;
41+ }
42+ } ;
43+ this . insert = function ( position , element ) {
44+ if ( position > - 1 && position <= length ) { //校验边界
45+ var node = new Node ( element ) ;
46+ current = head ;
47+ var index = 0 ;
48+ var previous ;
49+ if ( position == 0 ) { //作为头节点,将新节点的next指向原有的头节点。
50+ node . next = current ;
51+ head = node ; //新节点赋值给头节点
52+ } else {
53+ while ( index ++ < position ) {
54+ previous = current ;
55+ current = current . next ;
56+ } //遍历结束得到当前position所在的current节点,和上一个节点
57+ previous . next = node ; //上一个节点的next指向新节点 新节点指向当前结点,可以参照上图来看
58+ node . next = current ;
59+ }
60+ length ++ ;
61+ return true ;
62+ } else {
63+ return false ;
64+ }
65+
66+ } ;
67+ this . toString = function ( ) {
68+ var current = head ;
69+ var string = '' ;
70+ while ( current ) {
71+ // console.log(current)
72+ string += ',' + current . element ;
73+ current = current . next ;
74+ }
75+ return string ;
76+ } ;
77+ this . indexOf = function ( element ) {
78+ var current = head ;
79+ var index = - 1 ;
80+ while ( current ) {
81+ if ( element === current . element ) { //从头节点开始遍历
82+ return index ;
83+ }
84+ index ++ ;
85+ current = current . next ;
86+ }
87+ return - 1 ;
88+ } ;
89+ this . getLength = function ( ) {
90+ return length ;
91+ }
92+
93+ }
94+
95+ let linkList = new LinkedList ( )
96+ for ( let index = 0 ; index < 10 ; index ++ ) {
97+ linkList . append ( index )
98+ }
99+
100+ console . time ( 'start' )
101+ linkList . insert ( 1 , '呵呵哒' )
102+ console . timeEnd ( 'start' )
103+
104+
105+ // let arr = []
106+ // for (let index = 0; index < 1000000; index++){
107+ // arr.push(index)
108+ // }
109+ // console.time('start')
110+ // arr.unshift('呵呵哒')
111+ // console.timeEnd('start')
0 commit comments