Data Structures: Reverse a Doubly Linked List
This commit is contained in:
		
							parent
							
								
									44f36ee920
								
							
						
					
					
						commit
						5e17d76817
					
				
							
								
								
									
										25
									
								
								Data Structures/doublyLinkedListReverse.js
									
									
									
									
									
										Normal file
									
								
							
							
						
						
									
										25
									
								
								Data Structures/doublyLinkedListReverse.js
									
									
									
									
									
										Normal file
									
								
							@ -0,0 +1,25 @@
 | 
			
		||||
// https://www.freecodecamp.org/learn/coding-interview-prep/data-structures/reverse-a-doubly-linked-list
 | 
			
		||||
 | 
			
		||||
var Node = function (data, prev) {
 | 
			
		||||
  this.data = data;
 | 
			
		||||
  this.prev = prev;
 | 
			
		||||
  this.next = null;
 | 
			
		||||
};
 | 
			
		||||
var DoublyLinkedList = function () {
 | 
			
		||||
  this.head = null;
 | 
			
		||||
  this.tail = null;
 | 
			
		||||
  // Only change code below this line
 | 
			
		||||
  this.reverse = () => {
 | 
			
		||||
    const newTail = this.head;
 | 
			
		||||
    let node = this.head;
 | 
			
		||||
    while (node !== null) {
 | 
			
		||||
      const newPrev = node.next;
 | 
			
		||||
      node.next = node.prev;
 | 
			
		||||
      node.prev = newPrev;
 | 
			
		||||
      node = newPrev;
 | 
			
		||||
    }
 | 
			
		||||
    this.head = this.tail;
 | 
			
		||||
    this.tail = newTail;
 | 
			
		||||
  };
 | 
			
		||||
  // Only change code above this line
 | 
			
		||||
};
 | 
			
		||||
		Loading…
	
		Reference in New Issue
	
	Block a user