我在链接列表中的节点之间添加节点时遇到问题....我的代码如下
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();
}
我得到的结果用我提供的那个替换了Node ...所以我的问题是如何修改函数以在其间添加节点
答案 0 :(得分:0)
更改此部分:
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 ;
}