#1 1.4 查找链表的倒数第n个节点

152 阅读1分钟

查找链表的倒数第n个节点

原题链接[:](https://leetcode.cn/leetbook/read/illustration-of-algorithm/7f2ng5/)

代码记录

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode() {}
 *     ListNode(int val) { this.val = val; }
 *     ListNode(int val, ListNode next) { this.val = val; this.next = next; }
 * }
 */
class Solution {
    public ListNode trainingPlan(ListNode head, int cnt) {
        //使用hashmap
         int count=0;
         ListNode node=head;
         HashMap<Integer,ListNode> map=new HashMap<Integer,ListNode>();
         while(node!=null){
             map.put(count++,node);
             node=node.next;
         }
         return map.get(count-cnt);

       
    }
}
/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode() {}
 *     ListNode(int val) { this.val = val; }
 *     ListNode(int val, ListNode next) { this.val = val; this.next = next; }
 * }
 */
class Solution {
    public ListNode trainingPlan(ListNode head, int cnt) {

        //使用快慢指针==>p走过的步数刚好为整个链表长度 (p+q)/len=cnt
        ListNode p=head;
        ListNode q=head;
        while(cnt!=0){
            p=p.next;
            cnt--;
        }

        while(p!=null){
            p=p.next;
            q=q.next;
        }

        return q;

      
    }
}
/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode() {}
 *     ListNode(int val) { this.val = val; }
 *     ListNode(int val, ListNode next) { this.val = val; this.next = next; }
 * }
 */
class Solution {
    public ListNode trainingPlan(ListNode head, int cnt) {

        //使用栈
        Stack<ListNode> stack=new Stack<ListNode>();
        ListNode node=head;
        while(node!=null){
            stack.push(node);
            node=node.next;
        }
        while(cnt>1){
            stack.pop();
            cnt--;
        }
        return stack.pop();
    }
}
/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode() {}
 *     ListNode(int val) { this.val = val; }
 *     ListNode(int val, ListNode next) { this.val = val; this.next = next; }
 * }
 */
class Solution {
    int global=0;
    public ListNode trainingPlan(ListNode head, int cnt) {
        //使用后递归
        global=cnt;
        return recur(head);
    }
    public ListNode recur(ListNode head){
        if(head==null){
            return null;
        }
        ListNode temp=recur(head.next);
        global--;
        if(global==0){
            return head;
        }
        return temp;
    }
}