JAVA实验2 类和继承(2学时)List类

来源:互联网 发布:VB中的整型变量 编辑:程序博客网 时间:2024/05/17 03:18
package List;public class List<T>{private static class Node<T> {T nodeValue;Node<T> next;Node(T nodeValue, Node<T> next){this.nodeValue=nodeValue;this.next =next;}Node(T nodeValue){this.nodeValue=nodeValue;this.next=null;}}  private Node<T> head,p,q,m;  public List()  {  head=null;  }  public  boolean isEmpty()//判断链表是否为空  {  if(head==null)  {  return true;  }  else  {  return false;  }  }  public int Length()//返回当前链表中对象的个数  {  int size=0;  p=head;  while(p!=null)  {  size++;  p=p.next;  }  return size;  }  public void Add(T value) //在表尾添加某个对象  {  q=head;  p=new Node<T>(value);      if(!isEmpty())      {      while(q.next!=null)      {      q=q.next;      }      q.next=p;      p.next=null;      }      else      {      p.next=head;      head=p;      }  }  public void AddHead(T value)//在表头添加某个对象  {  p=new Node<T>(value);  p.next=head;  head=p;  }  public void getData(int n)//取得某个位置的对象。构造main函数进行测试。  {  int count=1;  if(n>Length())  {  System.out.println("对不起,你输入的值已超出范围");  }  else  {  p=head;  while(p!=null)  {  if(count==n)  {  System.out.println("第"+n+"个数值为:"+p.nodeValue);  break;  }  count++;  p=p.next;  }  }  }  public void Insert(int n,T value)//在某个位置插入对象  {  int count=1;  p=head;  m=new Node<T>(value);  while(p!=null)  {  if(count==n)  {  if(p!=head)  {  q.next=m;  m.next=p;  }  else  {  m.next=head;  head=m;  }  }  count++;  q=p;  p=p.next;    }  }  public void Delete(int n)//在某个位置删除对象  {  int count=1;  p=head;  while(p!=null)  {  if(count==n)  {  if(p!=head)  {  q.next=p.next;  }  else  {  head=head.next;  }  }  count++;  q=p;  p=p.next;    }  }  public void Delete_v(T x)//删除链表中与x相同的元素  {  p=head;  int flag=0;  while(p!=null)  {   if(p.nodeValue==x)  {  flag=1;  if(p!=head)  {  q.next=p.next;  }  else  {  head=head.next;  }  }  q=p;  p=p.next;  }  if(flag==0)  {  System.out.println("对不起没有找到元素:"+x);  }  }  public void Traverse()//遍历链表,打印出所有的元素  {  p=head;  System.out.print("遍历链表:");  while(p!=null)  {  System.out.print(p.nodeValue);  System.out.print(" ");  p=p.next;  }  System.out.println();  }  public static void main(String args[])  {  List<Object> L = new  List<Object>();  L.Add(4);  if(!L.isEmpty())  {  System.out.println("不空");  }  else  {  System.out.println("空");  }    L.Add(67);  L.Add(55);  L.AddHead(55);  L.AddHead(3);  for(int i=0;i<=L.Length();i++)  {  L.getData(i);  }  L.Traverse();  L.Insert(1,9);  L.Delete(5);  L.Delete(2);  L.Delete_v(5);  L.Delete_v(55);  L.Traverse();  }}


 

	
				
		
原创粉丝点击