1
我是编程初学者。我试图在java中实现链表我试图写函数来插入第n个位置的元素,但它不能正常工作,它没有显示数据之前的位置。这可能看起来愚蠢的问题或错误,但作为我的初学者,所以你的答案将是有益的,它将不胜感激。如何在链表中的第n个位置插入节点
谢谢先进。
该代码如下。
class Node{
int data;
Node next;
Node(){
data=0;
next=null;
}
}
class LinkedList{
Node head;
LinkedList(){
head=null;
}
void pushB(int item){
Node temp=new Node();
temp.data=item;
temp.next=null;
if(head==null){
head=temp;
}
else{
temp.next=head;
head=temp;
}
}
void pushnth(int item, int pos){
Node cur=new Node();
cur.data=item;
cur.next=null;
Node temp=head;
int i=0;
while(i<pos-1){
temp=temp.next;
i++;
}
cur.next=temp;
head=cur;
}
void print(){
if(head==null){
System.out.println("List empty");
}
else{
Node temp=head;
while(temp!=null){
System.out.println(temp.data);
temp=temp.next;
}
}
}
}
public class MyFirstJavaProgram {
public static void main(String []args) {
System.out.println("Hello World");
LinkedList l1=new LinkedList();
l1.pushB(90);
l1.pushB(80);
l1.pushB(70);
l1.pushB(60);
l1.pushB(50);
l1.pushB(30);
l1.pushB(20);
l1.pushB(10);
l1.pushnth(40,4);
l1.print();
}
}
非常感谢你@Eran。我知道了。 – Parvez
这里我们没有修改头部,但是头部如何给我们修改列表。 – Parvez
@Parvez如果你想让新节点成为第一个节点(你在'pushB'中做的),你只需要修改头部。当您在中间添加一个元素时,通过更改列表中的某个节点x的x.next来修改该列表。 – Eran