Title:
Given a list, delete list reciprocal of n nodes, and returns to the head node list.
Example:
Given a list: 1-> 2-> 3-> 4-> 5, and n = 2.
After removed when the penultimate node, the list becomes 1-> 2-> 3-> 5.
Description: to ensure that a given n is valid.
Advanced: Use one pass realized
: Interpretations
to first traverse the length of the list again to get the list, delete the penultimate n nodes is deleted positive first len-n + 1 nodes, delete:
/**
* 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) {
int len=0;
ListNode temp=new ListNode();
temp=head;
while(temp!=null){
temp=temp.next;
len++;
}
temp=head;
if(len==n) return head.next;//如果删除的是首元素则直接返回第二元素
for(int i=0;i<len-n-1;i++){
temp=temp.next;
}
temp.next=temp.next.next;
return head;
}
}
Or we can use a double pointer traversal method to find the element you want to delete. The first pointer is moved forward from the beginning of the list of step n + 1, and the beginning of the second list from the start pointer. Now, these two pointers are separated by n nodes. Let the constant interval maintained by simultaneously moving both hands forward, until the first pointer reaches the last node. At this time, the second pointer points to the n-th node starting from the last junction point. We re-link to the second node referenced by the pointer to the next pointer to the next node in this node.
/**
* 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) {
int len=0;
ListNode temp1=new ListNode(0);
ListNode temp2=new ListNode(0);
temp1=head;
temp2=head;
while(len!=n){
temp1=temp1.next;
len++;
}
if(temp1==null) return head.next;
while(temp1.next!=null){
temp1=temp1.next;
temp2=temp2.next;
}
temp2.next=temp2.next.next;
return head;
}
}
In fact, in order to reduce interference special circumstances (such as only one node, the first node to be deleted), we can use a dummy as the next node is the head node aid, dumb nodes, see the official specific ideas Solution:
Portal