如何往一个链表添加数据java_用java写的单向链表,第一个数据元素节点无法插入!!...

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(isize-1){

System.out.println("paraments is wrong");

}

if(i==-1){

return;

}

current=head.getNext();

for(int j=0;current!=null&&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);//<

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
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值