日期:2014-05-20 浏览次数:20941 次
class Node { Object data; //数据元素 Node next; //指向下一个节点 public Object getData() { return data; } public void setData(Object data) { this.data = data; } public Node getNext() { return next; } public void setNext(Node next) { this.next = next; } } class LinkList { Node head; //头节点 private int len; public LinkList(){ len=0; } public LinkList(Node node){ this.head=node; len=0; } public void add(Node node){ if(head==null){ head=node; len++; } else{ Node temp=head; while(temp.next!=null){ temp=temp.next; } temp.next=node; len++; } } public void remove(int index){ System.out.println(len); if(index>=len||index<0){ throw new ArrayIndexOutOfBoundsException(); } Node temp=head; while(temp.next!=null){ temp=temp.next; if(index==0){//0表示第一个元素. System.out.println("删除第一个"); Node n=head; head=n.next; n=null; break; }else if(index==len-1){ System.out.println("删除最后"); temp.next=null; break; }else{ System.out.println("删除中间"); Node nn=temp; temp=nn.next; nn=null; break; } } } public void display(){ Node temp=head; while(temp!=null){ System.out.println(temp); temp=temp.next; } } } class Test { public static void main(String[] args) { LinkList link=new LinkList(); Node n1=new Node(); link.add(n1); Node n2=new Node(); link.add(n2); Node n3=new Node(); link.add(n3); link.remove(1);//删除第二个元素,0表示第一个. System.out.println(n1); System.out.println(n2); System.out.println(n3); System.out.println("------------------------------------"); link.display(); } }
Node temp=head; int current = 0; while(temp.next!=null){ ...//代码不变 else if (current==index){ //循环到目标节点才执行 ...//代码不变 } current++; //节点位置+1 }