题目地址:
中文: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;
}
}