我在链接列表中的节点之间添加节点时遇到问题......我的代码如下
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/