java - 链表在位置添加

标签 java linked-list

我在链接列表中的节点之间添加节点时遇到问题......我的代码如下

public class Node {
    int data;
    int count;
    Node prev,next;
    public Node(int x){
        data=x;
        next=null;
        count=count++;
    }    
}

插入位置函数

public void insertAtPos(int x ,int pos){

    if (start==null) {
        Node p=new Node(x);
        start=p; 
        NodeCount=NodeCount+1;
    } else {
        int i=1;
        Node current=start;
        if (pos>0){
            if (pos>NodeCount){
                System.out.println("The position exceeds the nodes in Linked List");
            }
             while (current!=null){
                 if (i==pos-1){
                     Node p=new Node(x);
                     p.next=current.next;
                     current.next=p;
                     return ;
                 }else{
                     current=current.next;
                     i++; 
                 }
                 NodeCount=NodeCount+1;

             }
        }else{

            System.out.println("The position exceeds the nodes in LL");
        }
    }
}

主要

public static void main(String[]args){
        LinkedList s=new LinkedList();
        s.insertFront(55);
        s.insertFront(33);
        s.insertFront(75);
        s.insertFront(83);
        s.insertEnd(59);

        s.display();

        s.insertAtPos(44,2);
        System.out.println("  ");
        s.display();
    }

我得到的结果用我提供的节点替换了节点...所以我的问题是如何修改函数以在两者之间添加节点

最佳答案

更改这部分:

 if (i==pos-2){//stopping in previous node where you have to insert
       Node p=new Node(x);
       p.next=current.next;
       current.next=p;
       return ;
 }

关于java - 链表在位置添加,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47301611/

相关文章:

java - 捕获图像在 HTC 设备上崩溃

java - Spring Boot 通过 Netbeans 在 Tomcat 8 中运行 war 失败

java - 我有一个关于如何运行 springboot 项目的问题

java - System.out.print 不打印到控制台,否则打印新行

Java正则表达式在两个模式之间匹配

c - 如何对正在增长的链表中的 2 个节点进行所有可能的比较

java - 迭代深复制链接列表

c - 推送链接列表 - C

C 链表只包含第一个元素......不知道剩下的会发生什么

c - 在链表的开头插入?