链表问题 在双链表中删除倒数第K个节点

 要求:

时间复杂度O(n),空间复杂度O(1)。

思路总结:

首先自己创建双链表节点DuLNode,然后用for循环创建双链表(双向链表)。

第一遍遍历双链表,每移动一步,K--,遍历完后如果K < 0,则说明存在这个需要删除的节点。

第一遍遍历K的值K-N,则在第二遍遍历到K = 0时指针移到N-K的位置,要删除的节点位置是N-K+1。

收获:

会创建双向链表。

双链表不同于循环链表。

package com.company;

//此题是处理有序链表
public class Main {
    public static class DuLNode {
        public int value;
        public DuLNode prior;
        public DuLNode next;
        public DuLNode() { this.prior = null; this.next = null; }; //初始化一个空链表
        public DuLNode(int value) { this.value = value; }
    }//双链表

    public static void CreatNewDuLLinkedList2(DuLNode head, int[] a) {
        System.out.print("List is: ");
        DuLNode r = head;
        for (int i : a) {
            DuLNode p = new DuLNode(i);
            r.next = p;
            p.next = null;
            p.prior = r;
            r = r.next;
            System.out.print(p.value + " ");
        }
        r.next = null;
        System.out.println();
    }//尾插法

    public static DuLNode RemoveLastKthDuLNode(DuLNode dulnode, int LastKth) {
        if (dulnode == null || LastKth < 1) {
            return dulnode;
        }
        DuLNode p = dulnode;
        while (p != null) {
            LastKth--;
            p = p.next;
        }
        if (LastKth == 0) {
            dulnode = dulnode.next;
            dulnode.prior = null;
        }
        else if (LastKth > 0) {
            return p;
        }
        else if (LastKth < 0) {
            p = dulnode;
            while (++LastKth != 0) {
                p = p.next;
            }
            p.next = p.next.next;
            if (p.next != null)
                p.next.prior = p;
        }
        return dulnode;
    }

    public static void PrintDuLLinkedList(DuLNode duLNode) {
        System.out.print("List is: ");
        while (duLNode != null) {
            System.out.print(duLNode.value + " ");
            duLNode = duLNode.next;
        }
        System.out.println();
    }

    public static void main(String[] args) {
        int[] a = {1, 2, 3, 4, 6, 8, 9, 10};

        DuLNode dulhead = new DuLNode();

        CreatNewDuLLinkedList2(dulhead, a);
        dulhead = dulhead.next;
        dulhead.prior = null;
        //System.out.println(head2.next.next.value);

        System.out.println("============");

        RemoveLastKthDuLNode(dulhead, 2);
        PrintDuLLinkedList(dulhead);

    }
}

猜你喜欢

转载自blog.csdn.net/rivalak/article/details/81068688