public class Node {
Object element;
Node next;
public Node(Object element){
this.element=element;
}
public Node(Object element, Node next) {
super();
this.element = element;
this.next = next;
}
public Object getElement() {
return element;
}
public void setElement(Object element) {
this.element = element;
}
public Node getNext() {
return next;
}
public void setNext(Node next) {
this.next = next;
}
}public class LinList {
private Node head;//头指针
private Node current;//当前指针
private int size;//单链表的长度
public LinList(){
head=current=new Node(null);
size=0;
}
public void index(int i){//移动current指针的方法
if(i<-1||i>size-1){
System.out.println("paraments is wrong");
}
if(i==-1){
return;
}
current=head.getNext();
for(int j=0;current!=null&&j<i;j++){
current=current.getNext();
}
}
public void insert(int a,Object obj){
if(a<0||a>size){
System.out.println("your position isn't right");
}
index(a-1);//a-1的范围是【-1,size-1】
current.setNext(new Node(obj,current.getNext()));
size++;
}
public void Show(){
current=head.getNext();
while(current!=null){
System.out.print(current.getElement()+" ");
current=current.getNext();
}
}
public static void main(String[] args){
LinList ll=new LinList();
Node n=new Node(50,null);//<<--遍历出来的第一个数就是这里的50,但insert(0,0)没有反应
ll.head=new Node(null,n);
ll.insert(0, 0);
ll.insert(1, 1);
ll.insert(2, 2);
ll.insert(3, 3);
ll.insert(4, 4);
ll.Show();
}
}show()的结果:50 1 2 3 4 但我插入的是1 2 3 4 为什么第一个数没法替代呢?是不是书上的例子本身就有这个缺点呢?
添加回答
举报
0/150
提交
取消