Java实现简单的List

节点代码:
 1 //定义数据结构
 2 public class LinkNode {
 3     int value;
 4     LinkNode next;
 5     
 6     public LinkNode(int value){
 7     this.value = value;
 8     }
 9
 }
以上是定义的链表节点,可以在新建节点的时候赋值

链表节点:
public class MyList {
    
//定义首节点
    LinkNode first;
    
    
//定义尾节点
    LinkNode last;
    
    
//定义长度
    int length = 0;
    
    
public MyList(){
    first 
= null;
    last 
= null;
    }
    
    
public MyList(LinkNode node){
    first 
= node;
    last 
= node;
    length
++;
    }
    
    
//添加节点
    public void addNode(LinkNode node){
    
if(first == null){
        first 
= node;
        length 
= 1;
    }
    
else{
        last.next 
= node;
        last 
= node;
        length
++;
    }
    }
    
    
//删除指定节点:遍历链表,将遇到的第一个和指定节点相同的节点删去
    public void deleteNode(LinkNode node){
    
if(first == null){
        
return;
    }
        
    
else if(first.value == node.value){
        first 
= first.next;
        length
--;
    }
    
else{
        
//如果链表不为空,要删除也不是第一个
        LinkNode temp;
        System.out.println(node.value);
        
for(temp = first; temp != null ;temp = temp.next){
        
if(temp.next.value == node.value){
            
//如果下一个就是最后一个
            if(temp.next.equals(last)){
            last 
= temp;
            length
--;
            
return;
            }
            length
--;
            temp.next 
= temp.next.next;
            
return;
        }
        }
    }
    }
    
    
public int getLength(){
    
return length;
    }
}
以上是链表的具体实现,这里只实现了很简单的三个功能:添加节点,删除指定节点,获取链表长度。

接下来是测试代码:

public class Test {
    
public static void main(String[] args) {
    LinkNode node 
= new LinkNode(3);
    
    MyList list 
= new MyList(node);
    
    list.addNode(
new LinkNode(3));
    list.addNode(
new LinkNode(6));
    list.addNode(
new LinkNode(4));
    list.addNode(
new LinkNode(7));
    list.addNode(
new LinkNode(2));
    
    listDisplay(list);
    
    list.deleteNode(
new LinkNode(3));
    listDisplay(list);
    }
    
    
public static void listDisplay(MyList list){
    
int i = 0;
    
int length = list.getLength();
    LinkNode temp;
    
for(temp = list.first; i < length; temp = temp.next, i++){
        System.out.print(temp.value 
+ " ");
    }
    System.out.println();
    }
}
以下是输出结果:
3 3 6 4 7 2 
3 6 4 7 2 

程序有待改善的地方:
1.完善链表功能,比如插入功能(和添加什么的大同小异);
2.加强功能实现,可以通过一定的手段消除First的特殊性,使得实现更加简单;
3.可以使用泛型,是的链表的存储不局限于Integer类型;

posted on 2011-10-10 10:29 灰色客栈 阅读(594) 评论(0)  编辑  收藏


只有注册用户登录后才能发表评论。


网站导航:
 
<2011年10月>
2526272829301
2345678
9101112131415
16171819202122
23242526272829
303112345

导航

统计

常用链接

留言簿

随笔档案

文章档案

搜索

最新评论

阅读排行榜

评论排行榜