leetcode做题总结,题目Remove Nth Node From End of List 2012/01/27

本文深入探讨了如何通过双指针法删除链表中的倒数第N个节点,提供了具体实现代码及解析,帮助读者理解链表操作的核心逻辑。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

删除链表倒数第N的节点,也没什么难度,用两个指针相隔N个节点,然后同时向后移动,一个到末尾另一个就是第N个节点。

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) {
 *         val = x;
 *         next = null;
 *     }
 * }
 */
public class Solution {
    public ListNode removeNthFromEnd(ListNode head, int n) {
        ListNode newhead = new ListNode(0);
        ListNode start = new ListNode(0);
        ListNode end = new ListNode(0);
        newhead.next = head;
        end=newhead;
        start=newhead;
        
        for(int i=0;i<n;i++){
            if(end.next!=null){
                end=end.next;
            }else 
                return head;
        }
        while(end.next!=null){
            end=end.next;
            newhead=newhead.next;
        }
        newhead.next=newhead.next.next;
        return start.next;
    }
}

Update 2015/08/28: 上面的题目一上来直接创建三个节点我就呵呵了。。也不知道当时是怎么想的。下面来个正常的吧

/**
 * Definition for ListNode.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int val) {
 *         this.val = val;
 *         this.next = null;
 *     }
 * }
 */ 
public class Solution {
    /**
     * @param head: The first node of linked list.
     * @param n: An integer.
     * @return: The head of linked list.
     */
    ListNode removeNthFromEnd(ListNode head, int n) {
        // write your code here
        if (n <= 0) {
            return null;
        }
        
        ListNode start = new ListNode(0);
        start.next = head;
        
        ListNode p = start;
        for (int i = 0; i < n; i++) {
            if (head == null) {
                return null;
            }
            head = head.next;
        }
        while (head != null) {
            head = head.next;
            p = p.next;
        }
        p.next = p.next.next;
        return start.next;
    }
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值