Java 链表添加位置
我在链接列表的节点之间添加节点时遇到问题…我的代码如下Java 链表添加位置,java,linked-list,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 (s
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");
}
}
}
主要
我得到的结果将用我提供的节点替换该节点…因此我的问题是如何修改函数以在两者之间添加节点更改此部分:
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 ;
}
更改此部分:
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 ;
}
你在哪里调用'insertapos`?main函数..很抱歉忘了包括那一行我认为你的
节点类有问题。在构造函数中编写count=count++
,但尚未初始化要创建的节点的count。另外,通常,count
变量存储在LinkedList
的头部,以便于更新。我会在类节点上创建一个InsertAfter(Node newNode)
和InsertBefore(Node newNode)
方法,并在那里实现所需的逻辑。f、 e.InsertAfter:var temp=Node.next代码>到临时变量,设置Node.next=newNode代码>然后当newNote.next!=null跟随下一个节点并查找该节点链的末尾。然后endOfNodeChain.next=temp
使用node.InsertBefore(新节点(5))
然后应该处理它。删除计数
-我不明白为什么链接列表需要它。。。这只是在列表中插入/删除内容时必须跟踪的另一个变量。您可以动态计算它:public int Count{get{return 1/*或0如果您不想计算此节点,则应将其命名为ChidlCount或smth*/+(next为null?0:next.Count)
在哪里调用'insertapos`?main function.。很抱歉,忘记包含该行。我认为您的节点
类有问题。在构造函数中,您编写了count=count++
,但您正在创建的节点
的count尚未初始化。另外,count
变量通常存储在eLinkedList
以便于更新。我将创建一个InsertAfter(Node newNode)
和InsertBefore(Node newNode)
methode on class Node-并在那里实现所需的逻辑。f.e.InsertAfter:var temp=Node.next;
到一个temp var,设置Node.next=newNode;
then而newNote.next!=null跟随下一个节点并查找该节点链的末端。然后endOfNodeChain.next=temp;
使用Node.InsertBefore(新节点(5))
然后应该处理它。删除计数
-我不明白链接列表为什么需要它…这只是在从列表中插入/删除内容时必须跟踪的另一个变量。您可以动态计算它:公共int count{get{返回1/*或0如果您不想对该节点计数,则应将其命名为ChidlCount或smth*/+(next为null?0:next.count);