HoltYin

java链表的插入,删除,遍历(转)

public class Code {
private int data;
private Code next;
public int getData() {
 return data;
}
public void setData(int data) {
 this.data = data;
}
public Code getNext() {
 return next;
}
public void setNext(Code next) {
 this.next = next;
}
}


public class List {
 public Code head;
 List()
 {
  this.head=new Code();
  head.setData(0);
 }
 List(int n)
 {
  this.head=new Code();
  Code p,temp;
  p=head;
  for(int i=0;i<n;i++)
  {
   temp=new Code();
   temp.setData(i+1);
   p.setNext(temp);
   p=p.getNext();
  }
  head.setData(n);
 }
 //遍历节点
 public void rList()
 {
  Code temp;
  temp=head;
  while(temp.getNext()!=null)
  {
   temp=temp.getNext();
   System.out.println(temp.getData());
  }
 }
 //删除节点
 public void dCode(int n)
 {
  if(n>head.getData()){
   System.out.println("找不到第"+n+"个节点");
   return;
  }
  Code temp;
  temp=head;
  for(int i=0;i<n-1;i++)
  {
   temp=temp.getNext();
  }
  temp.setNext(temp.getNext().getNext());
  head.setData(head.getData()-1);
 }
 //插入节点
 public void iCode(int n,int d)
 {
  if(n>head.getData()+1){
   System.out.println("找不到第"+n+"个节点");
   return;
  }
  Code p=new Code();
  p.setData(d);
  Code temp;
  temp=head;
  for(int i=0;i<n-1;i++)
  {
   temp=temp.getNext();
        }
  p.setNext(temp.getNext());
  temp.setNext(p);
 }
 public static void main(String args[])
 {
  List l=new List(5);
  l.rList();
  l.iCode(3,8);
  l.rList();
  l.dCode(4);
  l.rList();
 }
} 

热评文章