算法总结之 在单链表和双链表中删除倒数第k个节点

分别实现两个函数,一个可以删除单链表中倒数第k个节点,另一个可以删除双链表中倒数第k个节点

思路:

  如果链表为空,或者k<1 参数无效 

  除此之外 让链表从头开始走到尾,每移动一步,就让k的值减1

   当链表走到头时候 如果k值大于0   说明不用调整  因为链表根本没有倒数第k个节点 此时将原链表直接返回即可

    如果k值=0,说明链表倒数第k个节点就是头节点,此时直接返回head.next 也就是原链表的第二个节点 让第二个节点作为链表的头节点,此时直接返回head.next 

    如果k值<0  重新从头开始走,没移动一步 k值加1   当k值等于0时,停止   移动到的节点就是要删除节点的前一个节点

废话不多说,上代码!

package TT;

public class Test85 {
 
      public class Node{
          public int value;
          public Node next;
          
          public Node(int data){
              this.value = data;
          }
               
      }
    
public static Node removeLastKthNode(Node head, int lastKth){
    
    if(head==null || lastKth<1){
        return head;
    }
    Node curNode = head;
    Node cur = head;
    
    while(cur!= null){
        lastKth--;
        cur=cur.next;
    }
    if(lastKth == 0){
        head = head.next;
    }
    if(lastKth<0){
        
        cur = head;
        while(++lastKth !=0){
          cur = cur.next;
        }
        cur.next = cur.next.next;
    }
    return head;
}
      
      
      
      
      
    
}

 双链表的问题,几乎与单链表处理如出一辙   要注意last指针的重连即可

package TT;

public class Test86 {

    public class DoubleNode{
        public int value;
        public  DoubleNode last;
        public  DoubleNode next;
        
        public DoubleNode(int data){
             this.value = data;
        }
    }
    
    
    public DoubleNode removeLastKthNode(DoubleNode head, int lastKht){
         if(head==null || lastKht<1){
             return head;
         }
         DoubleNode cur = head;
         while(cur!=null){
             lastKht--;
             cur = cur.next;
         }
         if(lastKht==0){
             head=head.next;
             head.last = null;
         }
         if(lastKht<0){
             
             cur = head;
             while(++lastKht !=0){
                 cur = cur.next;
             }
             DoubleNode newNext = cur.next.next;
             cur.next = newNext;
             if(newNext != null){
                 newNext.last =cur;
             }
         }
         
         return head;
         
         
    }
    
    
    
}
原文地址:https://www.cnblogs.com/toov5/p/7498693.html