在单链表和双链表中删除倒数第K个节点
先看单链表
如果链表为空或者K值小于1,直接返回即可,除此之外,让链表从头走到尾,每走一步,K值减一,如下图:
走到链表尾时:
-
当K>0,说明没有倒数第K个节点,因此直接返回原链表即可;
-
当K=0,说明链表刚好有K个节点,删除倒数第K个节点就是删除第一个节点,因此返回第二个节点,即head.next;
-
当K<0,要找到删除节点的前一个节点,需要:
1、重新从头节点开始走,每移动一步,k值加1;
2、当k=0时,移动停止,此时来到的节点就是要删除节点的前一个节点。
此时,倒数第2个节点是3,前一个节点是2。
具体代码
public class Node {
public int value;
public Node next;
public Node(int data){
this.value = data;
}
public static Node removeLastKthNode(Node head,int k){
if(k<1||head == null){
return head;
}
Node cur = head;
while(cur!=null){
k--;
cur = cur.next;
}
if(k == 0){
head = head.next;
}
if(k < 0){
cur = head;
while (++k != 0){
cur = cur.next;
}
cur.next = cur.next.next;
}
return head;
}
public static void print(Node head){
while (head != null){
System.out.print(head.value + " ");
head = head.next;
}
}
public static void main(String[] args) {
Node head1 = new Node(1);
head1.next = new Node(3);
head1.next.next = new Node(5);
head1.next.next.next = new Node(6);
System.out.print("原链表:");
print(head1);
System.out.println();
System.out.print("删除后链表:");
print(removeLastKthNode(head1,3));
}
}
输出结果
接下来是双链表
双链表的处理方式与单链表几乎一样,注意last指针的重连即可。
具体代码
public class DoubleNode {
public int value;
public DoubleNode next;
public DoubleNode last;
public DoubleNode(int data){
this.value = data;
}
public static DoubleNode removeLastKthNode(DoubleNode head,int k){
if(head == null || k <1){
return head;
}
DoubleNode cur = head;
while(cur!=null){
k--;
cur = cur.next;
}
if(k == 0){
head = head.next;
head.last=null;
}
if(k < 0 ){
cur = head;
while(++k!=0){
cur = cur.next;
}
DoubleNode newNext = cur.next.next;
cur.next = newNext;
if(newNext!=null){
newNext.last = cur;
}
}
return head;
}
public static void print(DoubleNode head){
while (head != null){
System.out.print(head.value + " ");
head = head.next;
}
}
public static void main(String[] args) {
DoubleNode head1 = new DoubleNode(1);
head1.next = new DoubleNode(2);
head1.next.next = new DoubleNode(3);
head1.next.next.next = new DoubleNode(4);
System.out.print("原链表:");
print(head1);
System.out.println();
System.out.print("删除后链表:");
print(removeLastKthNode(head1, 2));
}
}
输出结果