Reverse Linked List (opens in a new tab)
- Iterating through the list and reversing the direction of the next pointers of the nodes.
- After the entire list is reversed, the head pointer is updated to point to the new head of the list, which was the original tail.
/**
/**
* Definition for singly-linked list.
* function ListNode(val, next) {
* this.val = (val===undefined ? 0 : val)
* this.next = (next===undefined ? null : next)
* }
*/
/**
* @param {ListNode} head
* @return {ListNode}
*/
var reverseList = function(head) {
let prev = null,curr=head,next=null
while(curr!=null){
next = curr.next;
curr.next = prev;
prev = curr;
curr = next;
}
head = prev;
return head;
};
Complexity
- Time: O(n)
- Space: O(1)
Delete Node in a Linked List (opens in a new tab)
- Copy the data from the successor node into the current node to be deleted.
- Update the next pointer of the current node to reference the next pointer of the successor node.
/**
* Definition for singly-linked list.
* function ListNode(val) {
* this.val = val;
* this.next = null;
* }
*/
/**
* @param {ListNode} node
* @return {void} Do not return anything, modify node in-place instead.
*/
var deleteNode = function(node) {
node.val=node.next.val;
node.next=node.next.next;
};
Complexity
- Time: O(1)
- Space: O(1)