题目:
分别实现两个函数,一个可以删除单链表中倒数第K个节点,另一个可以删除双链表中倒数第K个节点。
要求
如果链表长度为N,时间复杂度达到O(N),额外空间复制度达到O(1)
代码:
public class removeLastKthNode {
public static class Node{
public int value;
public Node next;
public Node(int data)
{
this.value = data;
}
}
public static Node removeLastKthNode(Node head,int lastKth)
{
if(head==null||lastKth<1)
{
return head;
}
Node cur = head;
while(cur!=null)
{
lastKth--;
cur = cur.next;
}
if(lastKth==0)
{
head = head.next;
}
if(lastKth<0)
{
cur = head;
while (++lastKth!=0)
{
cur = cur.next;
}
cur.next = cur.next.next;
}
return head;
}
public static void main(String[] args) {
Node head =new Node(1);
Node cur = head;
int lastKth = 3;
for(int i = 2;i<10;i++)
{
Node temp = new Node(i);
cur.next = temp;
cur = temp;
}
cur = removeLastKthNode(head,lastKth);
for(int i = 1;i<9;i++)
{
System.out.print(cur.value+" ");
cur = cur.next;
}
System.out.println();
}
}
测试结果