删除链表的倒数第 N 个结点 (Remove Nth Node From End of List)

 

思路:

// @Title: 删除链表的倒数第 N 个结点 (Remove Nth Node From End of List)
// @Author: qisiii
// @Date: 2022-03-10 20:25:20
// @Runtime: 0 ms
// @Memory: 39.8 MB
// @comment: 
// @flag: 
/**
 * 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 removeNthFromEnd(ListNode head, int n) {
        ListNode fast=head;ListNode slow=new ListNode(-1,head),temp=slow.next;
        while(n>0){
            fast=fast.next;
            n--;
        }
        if(fast==null){
            return head.next;
        }
        while(fast!=null&&fast.next!=null){
            temp=temp.next;
            fast=fast.next;
        }
        temp.next=temp.next.next;        
        return slow.next;
    }
}

思路:

// @Title: 删除链表的倒数第 N 个结点 (Remove Nth Node From End of List)
// @Author: qisiii
// @Date: 2024-09-12 00:55:50
// @Runtime: 0 ms
// @Memory: 40.7 MB
// @comment: 
// @flag: 
/**
 * 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 removeNthFromEnd(ListNode head, int n) {
        ListNode old=new ListNode(-1,head),result=old;
        ListNode slow=head,fast=head;
        while(n>0){
            fast=fast.next;
            n--;
        }
        while(fast!=null){
            old=slow;
            slow=slow.next;
            fast=fast.next;
        }
        old.next=slow!=null?slow.next:null;
        return result.next;
    }
}

思路:依然还是双指针,唯一需要注意的时候,假如fast走到null了,那意味着要把头舍去

// @Title: 删除链表的倒数第 N 个结点 (Remove Nth Node From End of List)
// @Author: qisiii
// @Date: 2024-04-12 23:36:43
// @Runtime: 0 ms
// @Memory: 40.6 MB
// @comment: 依然还是双指针,唯一需要注意的时候,假如fast走到null了,那意味着要把头舍去
// @flag: BLUE
/**
 * 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 removeNthFromEnd(ListNode head, int n) {
        ListNode result=head,fast=head,old=new ListNode(-1,result);
        while(n>0){
            fast=fast.next;
            n--;
        }
        if(fast==null){
            return head.next;
        }
        while(fast!=null){
            old=old.next;
            fast=fast.next;
        }
        old.next=old.next.next;
        return result;
    }
}
Licensed under CC BY-NC-SA 4.0
最后更新于 2024-10-18