1.删除一个链表的倒数第K个节点,要求时间复杂度为O(n),额外的空间复杂度为O(1)
分析:三种情况 链表长度为num
1.num<K,不存在第K个节点。
2.num==K,删除第一个节点。
3.num>K,删除第num-k+1个节点。
public class Node {
public int value;
public Node next;
public Node(int data){
this.value=data;
}
}
public Node removeLastKthNode(Node head,int K){
if(head==null||K<1)
return head;
Node temp=head;
int num=0;
//计算节点总个数
while(temp!=null){
num++;
temp=temp.next;
}
//第二种情况
if(num==K){
return head.next;
}
//第三情况
if(num>K){
temp=head;
while(num-K!=0){ //定位到这个点的前驱 删除第num-K+1个节点 所以此节点前驱为 num-K
temp=temp.next;
num--;
}
//删除第num-K+1个节点
temp.next=temp.next.next;
}
return head;
}