题目地址
https://leetcode.com/problems/remove-nth-node-from-end-of-list/description/
题目描述
19. 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]
思路
- 通常这种题, 需要做个dummy.
- 快慢指针问题.
- 快指针先走n步. 然后快慢一起走, 当快指针走到尽头后, 在慢指针处进行删除.
- 最后return dummy.next.
关键点
代码
- 语言支持:Java
/**
* 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) {
if (head == null || n <= 0) {
return head;
}
ListNode dummy = new ListNode(0);
dummy.next = head;
for (int i = 0; i < n; i++) {
if (head == null) {
return null;
}
head = head.next;
}
ListNode preDelete = dummy;
while(head != null) {
preDelete = preDelete.next;
head = head.next;
}
preDelete.next = preDelete.next.next;
return dummy.next;
}
}
网友评论