JavaScript數據結構鏈表知識詳解

存儲有序的元素集合,但不一樣於數組,鏈表中的元素在內存中不是連續放置的。每一個元素由一個存儲元素自己的節點和一個指向下一個元素的引用(也稱指針或連接)組成。下面經過本文給你們詳細介紹下,須要的朋友參考下javascript

最近在看《javascript數據結構和算法》這本書,補一下數據結構和算法部分的知識,以爲本身這塊是短板。java

鏈表:存儲有序的元素集合,但不一樣於數組,鏈表中的元素在內存中不是連續放置的。每一個元素由一個存儲元素自己的節點和一個指向下一個元素的引用(也稱指針或連接)組成。node

好處:能夠添加或移除任意項,它會按需擴容,且不須要移動其餘元素。算法

與數組的區別:數組

    數組:能夠直接訪問任何位置的任何元素;數據結構

    鏈表:想要訪問鏈表中的一個元素,須要從起點(表頭)開始迭代列表直到找到所需的元素。app

作點小筆記。數據結構和算法

1this

2spa

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

52

53

54

55

56

57

58

59

60

61

62

63

64

65

66

67

68

69

70

71

72

73

74

75

76

77

78

79

80

81

82

83

84

85

86

87

88

89

90

91

92

93

94

95

96

97

98

99

100

function LinkedList(){

var Node = function(element){

this.element = element

this.next = null

}

var length = 0

var head = null

this.append = function(element){

var node = new Node(element)

var current

if(head == null){ //鏈表爲空

head = node

}else{ //鏈表不爲空

current = head

//循環鏈表,直到最後一項

while(current.next){

current = current.next

}

current.next = node

}

length ++ //更新鏈表長度

}

this.insert = function(position,element){

var node = new Node(element)

var current = head

var previous

var index = 0

if(position>=1 && position<=length){ //判斷是否越界

if(position === 0){ //插入首部

node.next = current

head = node

}else{

while(index++ < position){

previous = current

current = current.next

}

node.next = current

previous.next = node

}

length ++ //更新鏈表長度

return true

}else{

return false

}

}

this.indexOf = function(element){

var current = head

var index = -1

while(current){

if (element === current.element) {

return index

}

index++

current = current.next

}

return -1

}

this.removeAt = function(position){

if(position>-1 && position<length){ //判斷是否越界

var current = head

var previous

var index = 0

if(position === 0){ //移除第一個元素

head = current.next

}else{

while(index++ < position){

previous = current

current = current.next

}

previous.next = current.next //移除元素

}

length -- //更新長度

return current.element

}else{

return null

}

}

this.remove = function(element){

var index = this.indexOf(element)

return this.removeAt(index)

}

this.isEmpty = function(){

return length == 0

}

this.size = function(){

return length

}

this.toString = function(){

var current = head

var string = ""

while(current){

string = "," + current.element

current = current.next

}

return string.slice(1)

}

this.getHead = function(){

return head

}

}

相關文章
相關標籤/搜索