Topic:
Idea: If the list is empty or n is less than 1, return directly, otherwise, let the list go from head to tail, each move one step, let N minus 1.
1. List 1->2->3,n=4, there is no fourth node, return the entire list
Swept nodes in sequence:
n Worth changing: 3-2-1
2. Linked list 1->2->3,n=3
Swept nodes in sequence:
n Worth changing: 2-1-0
3. Linked list 1->2->3,n=2
Swept nodes in sequence:
n Worth changing: 1-0--1
When walking to the end of the list: 1.n>0, indicating that the list does not have the nth node, directly return to the original linked list;
2.n=0, indicating that the last nth node of the list is the head node, returning to the Head.next;
3.n<0, start from the beginning, do not move one step to let N plus 1, when the n=0, move stop, the current move to the node is to delete the node's previous node. Because if the list length is L, then the previous node of the nth-L-n is the second. When the first sweep to the end of the list, the value of n becomes n-l, and when N is added 1 until 0 o'clock, the second sweep is exactly the first l-n node.
/** * Definition for singly-linked list. * public class ListNode {* int val; * ListNode Next; * listnode (int x) {val = x;}}} */public class Soluti On {public ListNode removenthfromend (listnode head, int n) { if (head==null| | n<1) { return head; } ListNode Cur=head; while (cur!=null) { n--; Cur=cur.next; } if (n==0) { return head.next; } if (n<0) { cur=head; while (++n!=0) {//When n=0 moves stop, the node moved to is the previous node to delete the node cur=cur.next; } Cur.next=cur.next.next; } return head; }}
"Leetcode" 19. Remove Nth Node from End of List