create方法在链表前插入

ttvkxqim  于 2021-07-12  发布在  Java
关注(0)|答案(1)|浏览(262)

关闭。这个问题需要细节或清晰。它目前不接受答案。
**想改进这个问题吗?**通过编辑这个帖子来添加细节并澄清问题。

昨天关门了。
改进这个问题
我已经创建了一个insert-after方法,现在我必须通过修改我的方法来创建一个insert-before方法。我需要更改什么才能成为insert before方法?

public void insertAfter(int key, int input){
    Node ndInput = new Node(input, null);
    Node temp = head;
    do{
        if(temp.data == key){
            ndInput.next = temp.next;
            temp.next = ndInput;
            if(ndInput.next == null) tail = ndInput;
            break;
        }
        temp = temp.next;
    }while(temp != null);
}
zte4gxcn

zte4gxcn1#

首先,当列表为空时,当前代码将失败。此外,最好:
仅在找到密钥时创建节点
利用 Node 构造函数初始化 next 立即归还财产。
所以:

public void insertAfter(int key, int input) {
    Node temp = head;
    while (temp != null) { // Loop condition should be here, to deal with empty list
        if (temp.data == key) {
            temp.next = new Node(input, temp.next); // Create here & use 2nd arg
            if (temp == tail) tail = temp.next;
            break;
        }
        temp = temp.next;
    }
}

作出决定 insertBefore ,在中查找钥匙 temp.next 而不是在 temp . 因为您仍然需要处理空列表的情况,所以最好将其作为一个单独的条件。
当插入的节点成为第一个节点时,还需要调整头部。另一方面,不再需要检查插入的节点是否成为尾部,因为这当然是不可能的:

public void insertBefore(int key, int input){
    if (head == null) return; // Add as separate check
    if (head.data == key) { // Case where head needs to refer to new node
        head = new Node(input, head);
        return;
    }
    Node temp = head;
    while (temp.next != null) { // Check whether there is a next node
        if (temp.next.data == key) { // Check data in next node
            temp.next = new Node(input, temp.next);
            break;
        }
        temp = temp.next;
    }
}

相关问题