借鉴http://www.cnblogs.com/lixiaolun/p/4643886.html思路
初始化单链表,采用尾插法插入元素,打印该链表
采用相同的思路对链表进行了删除、获取链表长度、获取链表的第i个元素以及判断某元素是否存在该链表中等操作
public class LinkList {
class Element{//结点
public Object value = null ;
private Element next = null;
}
private Element head = null;//头结点
//初始化链表
void initList(){
head = new Element();
head.value = null ;
head.next = null ;
}
//尾插法 插入元素
void insert(Object o){
Element e = new Element() ;//一个新结点
e.value = o ;
if( head.next == null ){//第一次插入
head.next = e ;
}else{
Element temp = head ;//temp指向head这个头结点
while(temp.next!=null){
temp = temp.next ;//temp指向当前结点,令temp指向下一个结点
}
temp.next = e ;//当temp指向最后一个结点时,temp.next为null,此时令其等于e这个结点
}
}
//删除元素
void delete(Object o){
Element temp = head ;
int i = 0 ;
while( temp.next != null ){
if(temp.next.value.equals(o)){
temp.next = temp.next.next ;
System.out.println("您删除了链表中的"+o+"元素");
i++;//做一个标记,如果没有变化则表示没有进入到if语句中,所以表示没有该元素存在
}else {
temp = temp.next ;
}
}
if( i == 0 ){//一个问题,提示要删除的元素不存在
System.out.println("您要删除的元素"+o+"不存在");
}
}
//获取链表的长度
public int getLe(){
int i = 0 ;
Element temp = head ;
while(temp.next != null ){
i++;
temp = temp.next ;
}
return i;
}
//获取该链表的第i个元素
public Element getElement(int i){
if(i <= 0 || i > getLe()){
System.out.println("获取链表的位置有误!");
return null ;
}else{
Element temp = head ;
for(int j = 0 ; j < i ;j++ ){
temp = temp.next ;
}
return temp;
}
}
//判断某元素是否存在
public void isContain(Object o) {
Element temp = head ;
int i=0 ;
while( temp.next != null){
if(temp.next.value.equals(o)){
i++;//记次数,出现过几次
}
temp = temp.next ;
}
if( i == 0 ){
System.out.println("该链表中不存在元素"+o);
}else {
System.out.println("该链表中存在"+o+"元素,且出现"+i+"次");
}
}
//打印链表
void print(){
System.out.println("打印链表:");
Element temp = head ;
if( temp.next == null ){
System.out.println("该链表为空");
}
while( temp.next != null ){
temp = temp.next ;
System.out.print(temp.value + "\t");
}
System.out.println("");
}
public static void main(String[] args) {
// TODO Auto-generated method stub
LinkList list = new LinkList();
list.initList();
list.insert(1);
list.insert(2);
list.insert(3);
list.insert(4);
list.insert(5);
list.insert(5);
list.insert(3);
list.insert(4);
list.print();
// System.out.println("该链表的长度是"+list.getLe());
// list.delete(5);
// list.print();
// System.out.println("该链表的长度是"+list.getLe());
//System.out.println("该链表第2个元素是"+list.getElement(2).value);
list.isContain(5);
list.isContain(0);
}
}