Topic link
Leetcode-cn.com/problems/re…
Topic describes
Given a linked list, delete the NTH last node of the list and return the first node of the list.
Example:
Given a linked list: 1->2->3->4->5, and n = 2. When the penultimate node is deleted, the list becomes 1->2->3->5.Copy the code
Description:
A given n is guaranteed to be valid.
Advanced:
Can you try using a scan implementation?
The problem solving scheme
Train of thought
- Tags: linked lists
- The whole idea is to let the preceding pointer move first
n
Step, after which the front and back Pointers move together until the front pointer reaches the tail - First set up pre pointer, pre pointer is a trick explained in question 2
- Preset pointer
pre
The next node points tohead
, set the front pointer tostart
, the last pointer isend
Both of them are equal topre
start
I’m going to take n steps forward- after
start
andend
Moving forward together, the distance between the two is zeron
whenstart
When I get to the tail,end
Is exactly the penultimate positionn
A node - Because the node is to be deleted, it can only be deleted by moving to the previous node, so the end of the loop condition is
start.next ! = null
- Return after deletion
pre.next
Why not just returnhead
?head
It could be a deleted point - Time complexity: O(n)
code
/** * Definition for singly-linked list. * public class ListNode { * int val; * ListNode next; * ListNode(int x) { val = x; }} * * /
class Solution {
public ListNode removeNthFromEnd(ListNode head, int n) {
ListNode pre = new ListNode(0);
pre.next = head;
ListNode start = pre, end = pre;
while(n ! =0) {
start = start.next;
n--;
}
while(start.next ! =null) {
start = start.next;
end = end.next;
}
end.next = end.next.next;
returnpre.next; }}Copy the code
Draw solution
Background reply “algorithm”, join every day algorithm group feel algorithm directly to the soul, welcome to click on and forward