美文网首页
在单链表和双链表中删除倒数第K个节点

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

作者: Tank_Mao | 来源:发表于2021-02-02 20:13 被阅读0次

    单链表:

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

    相关文章

      网友评论

          本文标题:在单链表和双链表中删除倒数第K个节点

          本文链接:https://www.haomeiwen.com/subject/jifutltx.html