LeetCode T19 Remove Nth Node From End of List

题目地址:

中文:https://leetcode-cn.com/problems/remove-nth-node-from-end-of-list/
英文:https://leetcode.com/problems/remove-nth-node-from-end-of-list/

题目描述:

Given the head of a linked list, remove the nth node from the end of the list and return its head.

Follow up: Could you do this in one pass?

Example 1:
在这里插入图片描述

Input: head = [1,2,3,4,5], n = 2
Output: [1,2,3,5]

Example 2:

Input: head = [1], n = 1
Output: []

Example 3:

Input: head = [1,2], n = 1
Output: [1]

Constraints:

The number of nodes in the list is sz.
1 <= sz <= 30
0 <= Node.val <= 100
1 <= n <= sz

思路:

本题目要将倒数第n个结点从链表中删除,然后返回头结点。
如果先遍历一遍确定数量的话,这样需要遍历两遍。
可以设置双指针,间隔n,这样当后一个指向尾结点的时候,前一个指针就指向倒数第n个结点了。

题解:

/**
 * 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 res = new ListNode(0);
        res.next = head;
        ListNode first = res;
        ListNode second = res;
        //把后边的指针往后挪
        for(int i=0;i<n;i++){
            second = second.next;
        }

        while (second.next!=null){
            first = first.next;
            second = second.next;
        }

        first.next = first.next.next;

        return res.next;
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值