A linked list is made up of nodes, an object that has a value and a pointer. There are three types singly, doubly, and circular.
Singly linked list is only one way, can not go backward. It contains 2 key-value, value(val) and next.
Doubly linked list is two way, can go forward and backward. It contains 3 key-value, value(val), next, and previous(prev).
Normally, linked list are linear, the head being the first node and the tail being the last node, having the last pointer point to null.
Circular linked list have no end or no tail node. The so call last/tail node point to a Nth node instead of null.
Let create a new Node. Each node are not connected.
let one = new Node(1)
let two = new Node(2)
let three = new Node(3)
let four = new Node(4)
1 2 3 4 The node are connect to another using the next property.
one.next = two
two.next = three
three.next = four
1->2->3->4->nullVersion1
Node {
val: 1,
next: Node { val: 2, next: Node { val: 3, next: Node { val: 4, next: null} } }
}
Version2
Node {
val: 1,
next: Node {
val: 2,
next: Node {
val: 3,
next: Node{
val: 4,
next: null
}
}
}
}
To reverse a linked list, we need the .next to point to the previous node.
H T
1->2->3->4->null T H
null<-1<-2<-3<-4
function reverse(head) {
let previousNode = null
while(head !== null){
let nextNode = head.next
head.next = previousNode
previousNode = head
head = nextNode
}
return previousNode
}
- We need to first need to create a previous node and set it to null.
- We are currently at the head, node 1.
- While the head in not null, we can do something with it.
- We first need to create a temporary variable call nextNode. Using head.next, we assign nextNode = node 2.
- We now need to change the pointer direction, rather having the pointer point to node 2, we want pointer to point to the previousNode which is null.
- After changing the direction of .next from we can update the previousNode and the head to move onto the next iteration. Assign previousNode = node 1 and head = node 2.
- Remember order matter on how you call your variables.
previousNode = head previousNode = node 1
head = nextNode head = node 2head = nextNode head = node 2
previousNode = head previousNode = node 2
8. Lastly return previousNode. If the linked list that is given is not valid it will return null, else it will return the reverse linked list.