Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- class Node{
- constructor(data, nuxt =null){
- this.data = data;
- this.next = null;
- }
- }
- class LinkedList{
- constructor(){
- this.head = null;
- }
- //insertFirst
- insertFirst(data){
- this.head = new Node(data);
- }
- //insertLast
- insertLast(data){
- if(this.head === null){
- this.head = new Node(data);
- } else {
- let node = this.head;
- while(node.next){
- node = node.next;
- }
- node.next = new Node(data);
- }
- }
- //size
- size(){
- let node = this.head;
- let counter = 0;
- while(node){
- node = node.next;
- counter++;
- }
- return counter;
- }
- //getFirst
- getFirst(){
- return this.head;
- }
- //getLast
- getLast(){
- let node = this.head;
- while(node){
- if(!node.next){
- return node;
- }
- node = node.next;
- }
- }
- //insertFirst
- insertFirst(item){
- this.head = new _Node(item, this.head);
- }
- //getAt
- getAt(index){
- let node = this.head;
- let counter = 0;
- while(node){
- if(index === counter){
- return node;
- }
- node = node.next;
- counter++;
- }
- }
- //removeAt
- removeAt(index){
- let previous = this.getAt(index-1);
- previous.next = previous.next.next;
- }
- //insertAt
- insertAt(index, data){
- let previous = this.getAt(index-1);
- const node = new Node(data, previous.next);
- previous.next = new Node(data);
- }
- //reverse
- reverse(){
- let curr = this.head;
- let previous = null;
- while(curr){
- let next = curr.next;
- curr.next = previous;
- previous = curr;
- curr = next;
- }
- return previous;
- }
- insertAfter(inList, insertVal){
- let node = this.head;
- while(node){
- if(node.data === inList){
- node.next = new Node(insertVal);
- }
- node = node.next;
- }
- }
- insertBefore(inList, insertVal){
- if(this.head.data === inList){
- this.head = new Node(insertVal);
- }
- let previous = this.head;
- let curr = this.head.next;
- while(curr){
- // console.log('this is curr', curr);
- if(curr.data === inList){
- console.log('this is firing');
- previous.next = new Node(insertVal);
- }
- previous = curr;
- curr = curr.next;
- }
- }
- thirdFromEnd(){
- let countTo = this.size()-3;
- console.log('this is countTo', countTo);
- let counter = 0;
- let node = this.head;
- while(node.nnext){
- if(counter === countTo){
- return node;
- }
- node = node.next;
- counter++;
- }
- }
- Middle(){
- let fast = this.head;
- let slow = this.head;
- while(fast.next && fast.next.next){
- slow = slow.next;
- fast = fast.next.next;
- }
- return slow;
- }
- Cycle(){
- let fast = this.head;
- let slow = this.head;
- while(fast.next && fast.next.next){
- if(slow === fast){
- return true;
- }
- slow = slow.next;
- fast= fast.next.next;
- }
- return false;
- }
- }//class end
- let pets = new LinkedList();
- pets.insertLast('kitten');
- pets.insertLast('puppy');
- pets.insertLast('parrot');
- pets.insertLast('hamster');
- pets.insertLast('farrett');
- console.log(pets.Middle());
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement