在单链表和双链表中删除倒数第K个节点

2021-02-02  本文已影响0人  Tank_Mao

单链表:

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的重连即可。

上一篇下一篇

猜你喜欢

热点阅读