两个给定的类:
public class Node {
int data;
Node next;
Node(int d, Node n){
data = d;
next = n;
}
}
public class List{
Node header;
}
编写一个Java方法insertNodeBefore,它使用两个整数int a(这是我们要插入的新节点的数据)和int b(这是我们需要在其之前插入新节点的节点的数据)列表我的清单...
以下是我所拥有的,我不确定:
public void insertNodeBefore(int a, int b) {
ListNode newNode = new ListNode();
newNode.data = b;
header.next = newNode;
header.next.next = newNode.next;
}
答案 0 :(得分:0)
插入方法如下所示,进行一些测试
public void insert(Node head,int a,int before){
Node prev = null;
while(head!=null){
// Matched at head;
if(prev==null && head.a==before){
Node fresh = new Node(a);
fresh.next=head;
head=fresh;
break;
} else if(head.a==before){
Node fresh = new Node(a);
fresh.next=head;
prev.next = fresh;
break;
}
prev = head.next;
head = head.next;
}
}