topic
Given a list, delete list reciprocal of n nodes, and returns to the head node list.
Complexity guarantee o (n)
Examples
Given a list: 1-> 2-> 3-> 4-> 5, and n = 2.
When the removed penultimate node, the list becomes 1-> 2-> 3-> 5.
n is effective to ensure
Thinking
Complexity is o (n), it is clear that only allow us to iterate over the list. We use double pointer, head2 point to the n + 1 nodes, head1 point to the head node, and then two pointers while traversing back until head2.next is empty, then the time is the penultimate head1 n + 1 nodes, to draw their own Figure it is better understood, following directly on the code.
Code
public class problem19 {
// Definition for singly-linked list.
public static class ListNode {
int val;
ListNode next;
ListNode(int x) {
val = x;
}
}
//删除倒数第n个元素,保证n有效
public ListNode removeNthFromEnd(ListNode head, int n) {
//一共两个指针
ListNode head1=head;//保存前面的指针
ListNode head2=head;//保存与head1相距n的指针
//首先找到第n个链表节点
while(n!=0&&head2!=null){
head2=head2.next;
n--;
}
//特殊情况,链表一共只有n个节点
if(head2==null) return head.next;
// System.out.println("head2:"+head2.val);
//head1,head2同步向后遍历
while(head2.next!=null){
head1=head1.next;
head2=head2.next;
}
//删除节点
head1.next=head1.next.next;
return head;
}
public static void main(String[] args) {
problem19 pro=new problem19();
ListNode a=new ListNode(1);
a.next=new ListNode(2);
a.next.next=new ListNode(3);
a.next.next.next=new ListNode(4);
a.next.next.next.next=new ListNode(5);
ListNode b=pro.removeNthFromEnd(a, 3);
while(b!=null){
System.out.println(b.val);
b=b.next;
}
}
}