LeetCode22、删除单链表的倒数第n个节点

题目描述

https://leetcode-cn.com/problems/lian-biao-zhong-dao-shu-di-kge-jie-dian-lcof/
在这里插入图片描述

解法

1、利用递归:

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */
class Solution {
    
    
    int count = 0;
    public ListNode getKthFromEnd(ListNode head, int k) {
    
    
       return reverse(head,k);

    }
    public ListNode reverse(ListNode head,int k){
    
    
        if(head==null) return head;
       
        ListNode last = reverse(head.next,k);//利用栈的回退
        count++;//完成一个返回则++,
        if(count==k){
    
    
            return head;
        }
        return last;
        
    }
}

在这里插入图片描述
2、双指针,利用快指针和慢指针的特性
先让快指针走k步,然后两个指针同步走,当快指针走到头时,慢指针就是链表倒数第k个节点。

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */
class Solution {
    
    
    int count = 0;
    public ListNode getKthFromEnd(ListNode head, int k) {
    
    
       if(head==null)
            return null;
        ListNode slow = head,fast = head;
        while(k>0 && fast!=null){
    
    
            fast = fast.next;
            k--;
        }
        while(fast!=null){
    
    
            fast = fast.next;
            slow = slow.next;
        }        
        return slow;
    }
}

在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/qq_44861675/article/details/114805250