java中虽没有指针之说,但却也能实现同指针一样的功效。
- ///节点//
- class node
- {
- public double x;
- public node next;
- public node pre;
- node (double x,node n)
- {
- this.x =x;
- this.pre =null;
- this.next =n;
- }
- node (double x)
- {
- this.x =x;
- }
- public node getnext()
- {
- return next;
- }
- public void setnext(node next)
- {
- this.next =next;
- }
- public node getpre()
- {
- return pre;
- }
- public void setpre(node pre)
- {
- this.pre =pre;
- }
- /*public node(double x,node next)
- {
- this.x=x; this.next =next;
- }*/
- }
- ///链表实现///
- class list
- {
- public node head,tail;
- public int length;
- list()
- {
- head= tail =null;
- }
- public boolean isEmpty()//判断是否为空
- {
- return head==null;
- }
- public void addhead(double x)// 加入head节点 一般调用一次
- {
- head=new node (x,null);
- //pt.setnext(head.getnext());
- //head.setnext(pt);
- if(tail==null) tail=head;
- }
- public void addtail(double x)// 往后 添加节点
- {
- if(!isEmpty())
- {
- tail.next =new node(x);
- tail=tail.next ;
- }else
- {
- head=tail =new node(x);
- }
- }
- public void print()
- {
- for(node temp=head;temp!=null;temp=temp.next )
- {
- System.out.print(temp.x +" ");
- }
- System.out.println("");
- }
- public void addnow(double x,double y)//在特定的位置 插入一个节点
- {
- for(node temp=head;temp!=null;temp=temp.next )
- {
- if(temp.x ==x )
- {
- node now= temp.next ;
- node ne=new node(y);
- temp.next =ne;
- ne.next =now;
- }
- }
- }
- }
- //
- public class test {
- /**
- * @param args
- */
- public static void main(String[] args) {
- // TODO Auto-generated method stub
- list k=new list();
- k.addtail(1);
- k.addtail(2);k.addtail(4);k.addtail(5);
- k.addnow(2, 3);//在2之后,插入为3的节点
- k.print();
- }
- }