Given a single linked list head pHead of length n, invert the list to return the new list head.

A quick review of linked lists

  • How to implement a linked list

    Class LinkedList{constructor(){this.count=0 // Define the number of elements stored in the list this.head=undefined // Data structure is dynamic, Save a reference to the first element}} // to represent the element in the list, Class Node{constructor(Element){this.element=element this.next=undefined // when the Node instance is created Its next pointer is always undefined}}Copy the code

The linked list method

  • Adds a new element to the end of the list

    push(ele){ let current=new Node(ele) if(! this.head){ this.head=current }else{ let temp=this.head while(temp.next){ temp=temp.next } temp.next=current } this.count++ }Copy the code
  • Removes an element from a linked list

    remove(idx){ if(idx>=0&&idx<this.count){ let pre; let current =this.head if(idx==0){ this.head=current.next }else{ let temp=this.head for(var i=0; i<idx; i++){ pre=current current=current.next } pre.next=current.next } this.count-- return current } return undefined }Copy the code
  • Access to elements

    getElementByIdx(idx){ if(idx>=0&&idx<this.count){ let current=this.head for(let i=0; i<idx; i++){ current=current.next } return current }else{ return undefined } }Copy the code
  • Insert elements in any position

    insert(ele,idx){ let node = new Node(ele) if(idx>=0&&idx<this.count){ if(idx==0){ let temp=this.head this.head=node This.head. Next =temp}else{let current= this.getelementByidx (idX-1) console.log(current); let temp=current.next current.next=node node.next=temp } } this.count++ }Copy the code

Reverse linked list:

reverse(){ if(! this.head) return let current=this.head let temp; let pre; while(current){ temp=current.next current.next=pre pre=current current=temp } return pre }Copy the code