作者:林子木 博客网址:http://blog.csdn.net/wolinxuebin
参考网址:http://blog.csdn.net/sunsaigang/article/details/5751780
描述:使用java实现简答的单链表的功能
定义了一个MyList类
包含的函数:
getHead()返回头指针;
isEmpty() 判断是否为空;
addFirst(T element)在链表的头部加入元素;
addLast(T element)在链表的尾部加入元;
add(T fix,T element)在指定元素fix后插入新的元素
remove(T element) 删除指定元素
contains(T element)查看是否包含某元素
printList()打印链表。
其他:
使用泛型
程序代码如下:
public class MyList<T>{ //使用泛型
/*
* 定义节点类Node
*/
private static class Node<T>{
T element;
Node<T> next;
Node(T element,Node<T> next){ //构造函数
this.element = element;
this.next = next;
}
Node(T element){ //构造函数
this(element,null); //调用上面的构造函数
}
}
//定义MyList成员
private Node<T> head; //定义头结点
/*
*构造函数
*/
MyList(){
head = null;
}
/*
*返回头指针
*/
public Node<T> getHead(){
return head;
}
/*
*查看链表是否为空
*/
public boolean isEmpty(){
return null == head; //判断是否为空
}
/*
*将元素加入链表头
*/
public void addFirst(T element){
if(isEmpty()) head = new Node<T>(element);
else head = new Node<T>(element,head);
}
/*
*将元素加入链表尾
*/
public void addLast(T element){
if(isEmpty()) head = new Node<T>(element);//如果为空
else {
Node<T> node = head; //不为空,就使用查找,知道表尾
while(node.next != null) node = node.next;
node.next = new Node<T>(element);
}
}
/*
*在指定元素后加入新元素
*/
public boolean add(T fix,T element){
if(isEmpty()) return false;
else {
Node<T> node = head; //定义中间变量
while(node.element != fix && null != node.next){//程序跳出条件为1、到表尾 2、找到这个元素
node = node.next; //查找是否含有元素
}
//这里采用直接使用while查找,而判断在while外面,可以加快速度
if(node.element == fix){ //这里首先判断是否找到元素
node.next = new Node<T>(element,node.next) ;//将element插入,并将element的next指向下一个元素
return true;
}
else
return false;
}
}
/*
*删除指定元素
*/
public boolean remove(T element){
if(isEmpty()) return false;
Node<T> node = head; //定义变量pre 和 node
Node<T> pre = null;
while(node.element != element && null != node.next){ //程序跳出条件为1、到表尾 2、找到这个元素
pre = node; //保存前面的变量
node = node.next; //指向下一个元素
}
if(node.element == element){
if(null == pre) //如果是指定元素是第一个元素
head = head.next;
else
pre.next = node.next;
return true;
}
else
return false;
}
/*
*查看是否包含某元素
*/
public boolean contains(T element){
if(isEmpty()) return false;
else {
Node<T> node = head;
while(node.element != element && null != node.next)//程序跳出条件为1、到表尾 2、找到这个元素
node = node.next; //不断指向下一个程序
if(node.element == element)
return true;
else
return false;
}
}
/*
*打印链表
*/
public void printList(){
if(isEmpty()){
System.out.println("null");
}
else{
for(Node<T> node=head; node!=null;node=node.next)
System.out.print(node.element +" ");
System.out.println(); //打印回车
}
}
public static void main(String[] args) {
MyList<Integer> list = new MyList<Integer>();//若不加<Integer>便是为指定参数类型,将会警告
//使用了未经检查或不安全的操作。
//有关详细信息, 请使用 -Xlint:unchecked 重新编译。
for(int i=0; i<10; i++){
list.addFirst(i);
}
list.printList(); //打印
list.remove(0); //删除
list.printList(); //打印
list.addLast(0); //在尾部加入
list.printList(); //打印
list.add(7,-7); //在7之后插入-7
list.printList(); //打印
if(list.contains(-7))
System.out.println("is in the list !");
else
System.out.println("is not in the list !");
}
}