单链表:
package pers.mao.linkedList.demo_02;
/**
* @author Mao Qingbo
* @date 2021-02-01
*/
public class RemoveLastKthNode {
public 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){
return cur.next;
}
while (lastKth < 0){
cur = head;
while (++lastKth != 0){
cur = cur.next;
}
cur.next = cur.next.next;
}
return head;
}
}
对于双链表,几乎与单链表一模一样,只需注意last的重连即可。
网友评论