Tag: Suppose code establishes the node from Val question Rem end
The task is more classic, in the case of a single-link list to complete the end of the nth node Delete:
Set up three nodes:
Cur record the current node location.
Ans Record the first of the nodes to be deleted
H record the table header position of the linked list
Assuming that you want to delete the nth point (which ensures that the deletion is valid), the ANS node should go to the last n+1 node in order to delete the bottom 3rd node directly cur.
The ANS is cur to walk the N nodes only to leave, to ensure that cur to the end of the list traversal, Ans.next point to delete the node
Finally, return the header h that deletes the node.
Program AC, but there is a case, that is, if the length of the list of N, delete the last nth point, the original algorithm will always fail, only for the case use return h.next, and do not want to understand
The procedure is as follows:
/**
* 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) {
if (Head.next = = null) {
return null;
}
ListNode cur = new ListNode (0);
ListNode ans = new ListNode (0);
cur = head;
Ans.next = head;
int count = 1;
while (cur! = null) {
if (Count > N) {
ans = ans.next;
}
cur = cur.next;
Count + +;
}
if (Ans.next = = head) return head.next; Ans Does not move, the list of length n is deleted from the last nth node, using the delete in else is invalid
else{
Ans.next = Ans.next.next;
return head;
}
}
}
The 19th question of 2018.9.30 Leetcode brush question Diary