This is the 16th day of my participation in Gwen Challenge
Other ways to implement linked lists
In the previous three sections we learned what a LinkedList is and implemented the append, removeAt, and insert methods. In this section we’ll implement the other methods of the LinkedList class.
toString
The toString method converts the linkedList object to a string.
function LinkedList () {
/ / the node class
let Node = function (element) {
this.element = element
this.next = null
}
// List number
let length = 0
// Reference to the first node
let head = null
this.toString = function () {
let current = head
let string = ' '
while (current) {
string += ', ' + current.element
current = current.next
}
return string.slice(1)}}Copy the code
First, to turn a list into a string output, we need to loop the list from beginning to end. The starting point is head, and the variable used for the loop is current, whose initial value is head, and if current exists, we concatenate current. Element. And points current to the next item, current. Next, until current does not exist and breaks out of the loop to return the final concatenated string
indexOf
The indexOf method takes the value of an element and returns its position if it is found in the list, otherwise -1
function LinkedList () {
/ / the node class
let Node = function (element) {
this.element = element
this.next = null
}
// List number
let length = 0
// Reference to the first node
let head = null
this.indexOf = function (element) {
let current = head
let index = 0
while (current) {
if(current.element === element){
return index
}
index++
current = current.next
}
return -1}}Copy the code
To compare whether the value passed in is in the list, or whether we need to loop the list from beginning to end, or whether we use current as the loop variable with an initial value of head and declare index to mark the position at which element is found. The initial value is 0 and the loop starts. If current is present, compare element to the element of the current item, if it is, return index, if not, add index and point current to current. Next. If current is empty, it is at the end of the list or the list is empty. The loop does not execute and returns -1
Remove, isEmpty, Size, and getHead methods
Now that we’ve implemented the previous methods, it’s easy to implement the rest
function LinkedList () {
/ / the node class
let Node = function (element) {
this.element = element
this.next = null
}
// List number
let length = 0
// Reference to the first node
let head = null
this.remove = function (element) {
let index = this.indexOf(element)
return this.removeAt(index)
}
this.Empty = function () {
return!!!!! length }this.size = function () {
return length
}
this.getHead = function () {
return head
}
}
Copy the code
At this point, we’ve implemented all of the linked list methods.