| Title: |
Remove Nth Node from End of List |
| Pass Rate: |
28.5% |
| Difficulty: |
Brief answer |
Given A linked list, remove the nth node from the end of the list and return its head.
For example,
n = 2. After removing the second node from the end, the linked list becomes 1->2->3->5.
Note:
Given n would always be valid.
Try to do the in one pass.
This question is very clear is to delete the last number of a node, I did not consider the beginning of the only one to go through, I first check a few, and then go to delete, which to consider the deletion is the head node and tail nodes,
The code looks more complicated, as follows:
1 /**2 * Definition for singly-linked list.3 * public class ListNode {4 * int val;5 * ListNode Next;6 * ListNode (int x) {7 * val = x;8 * next = null;9 * }Ten * } One */ A Public classSolution { - PublicListNode Removenthfromend (ListNode head,intN) { - intLen=1; theListNode temp=head; -ListNode result=head; - - if(head==NULL)return NULL; + while(temp.next!=NULL){ -len++; +temp=Temp.next; A } at if(len==1)return NULL; - if(n==Len) { -Head=Head.next; - returnhead; - } - for(inti=0;i<len-n-1;i++){ inHead=Head.next; - } to if(head.next.next==NULL){ +head.next=NULL; -}Else{ thehead.next=Head.next.next; * } $ Panax Notoginseng returnresult; - } the}
Then I can not remember how a trip, I found on the internet to find out or with two pointers, I think about how to do, the front has done a list of links to the topic of the ring, once again such a problem if the time complexity is O (n) or can only be traversed once the words are basically to consider two pointers, First, run the pointer to the end, and then run the pointer to the node to delete the previous node, two pointers in the middle of the difference N, but if the element to be deleted is the head node is to be dealt with separately, because the pointer difference n step, so if it is deleted head node then run to the end of the pointer to go down, Using this cross-border problem to handle the head pointer, if the head pointer in the back run encountered next is empty, it means to delete the head node, directly to head. Next on the line.
The specific code is as follows:
1 /**2 * Definition for singly-linked list.3 * public class ListNode {4 * int val;5 * ListNode Next;6 * ListNode (int x) {7 * val = x;8 * next = null;9 * }Ten * } One */ A Public classSolution { - PublicListNode Removenthfromend (ListNode head,intN) { -ListNode first=head,second=head; the for(inti=0;i<n;i++){ - if(second.next==NULL){ -Head=Head.next; - returnhead; + } -Second=Second.next; + } A while(second.next!=NULL){ atSecond=Second.next; -first=First.next; - } -first.next=First.next.next; - returnhead; - in } -}
Leetcode------Remove Nth Node from End of List