删除链表中倒数第n个节点

143 阅读1分钟

删除链表中倒数第n个节点

描述

给定一个链表,删除链表的倒数第 n 个节点并返回链表的头指针

要求:空间复杂度 O(1)O(1),时间复杂度 O(n)O(n)

解法1 : 获取倒数第n节点的正序位置

function removeNthFromEnd( head ,  n ) {
  let temp=head,count=0,delNum=0,pre=null;
  while(!temp.next){
    count++
    temp=temp.next  
  }                 // 目的为了获取链表的长度
  temp=head  
  delNum=count-n    // 获取倒数第n个节点的正序位置
  if(delNum){ 
     while(delNum>0&&temp.next){
           delNum--
           pre=temp
           temp=temp.next   
     }
      pre.next=temp.next // 删除temp元素
  }else{
      head=head.next // 当删除节点索引为0
  }
}

解法2 : 双指针

function removeNthFromEnd( head ,  n ) {
    let slow=head,fast=head
    while(n>0){
      fast=fast.next
      n--
    }                   
    if(fast===null){
      slow=slow.next
      return
    }
    while(fast.next){
      fast=fast.next
      slow=slow.next
    }
    slow.next=slow.next.next
    return head
}

\