繁体   English   中英

如何使用自定义方法在第 0 个位置的链表中插入节点?

[英]How do I insert a node in linked list at 0th position using a custom method?

我已经创建了一个方法来在 LinkedList 中的第 N 个索引处插入一个节点。 该代码适用于除第 0 个位置以外的所有位置。 请查看下面的代码,让我知道出了什么问题。 下面的代码有 2 个插入方法:

  1. insert(int data) :这用于添加新节点。
  2. insertAtNthPositon(int position, int data) :这有助于在第 N 个位置插入元素。
public class LinkedList {
    Node head;

    static class Node {
        int data;
        Node next;
    }

    public void insert(int data) {
        Node new_node = new Node();
        new_node.data = data;
        new_node.next = null;

        if (head == null) {
            head = new_node;
        } else {
            Node n = head;
            while (n.next != null) {
                n = n.next;
            }
            n.next = new_node;
        }
    }

    public void insertAtNthPositon(int position, int data) {
        Node new_node = new Node();
        new_node.data = data;
        Node current_node = head;

        int i = 0;
        if (position == 0) {
            new_node.next = current_node.next;
            head = new_node;
            current_node = current_node.next;
        }
        while (i < position - 1) {
            current_node = current_node.next;
            i++;
        }
        new_node.next = current_node.next;
        current_node.next = new_node;
    }

    public static void main(String[] arg) {

        LinkedList ls = new LinkedList();
        ls.insert(6);
        ls.insert(7);
        ls.insert(9);
        ls.insertAtNthPositon(1, 100);
        ls.show();

    }

    private void show() {
        Node current = head;
        StringBuilder sb = new StringBuilder();
        do {
            sb.append(current.data);
            sb.append("->");
            current = current.next;
        } while (current != null);
        sb.append("null");
        System.out.println(sb.toString());
    }
}

输出:

6->100->7->9->空

正如我所建议的:您需要将 [at: if (position == 0)] new_node.next 设置为 current_node 而不是 current_node.next -> 这就是为什么您总是从索引 1 而不是 0 开始。

   public void insertAtNthPositon(int position, int data){
    Node new_node = new Node();
    new_node.data =data;
    Node current_node = head;

    int i = 0;
    if (position == 0){
        **new_node.next = current_node;** <instead of current_node.next>
        head = new_node;
        current_node = current_node.next;
    }
    while(i < position - 1){
        current_node = current_node.next;
        i++;
    }
    new_node.next = current_node.next;
    current_node.next = new_node;
}

顺便说一句-ls.insertAtNthPositon(1, 100); 在索引 1 处插入 100,你想要做 ls.insertAtNthPositon(0, 100); 为了让“100”成为第一个。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM