链表的实现(Java)

链表是一种基本的数据结构,与数组相比链表存储数据更为灵活。在本实例中,实现的是链表结构,使用Java语言实现。
链表类的设计,链表由链节点构成,每个链节点分别由数据域(value)和节点域(next)组成,数据域用于存储数据,节点域用于指向下一个节点。
class Node{
    int value;//数据域
    Node next;//节点域
    public Node(int data){
        this.value=data;//节点类构造函数
    }
}

public class LinklistNode {
    Node node;//节点

    public LinklistNode(){
        this.node=null;//链表构造函数
    }

    public Node initLinklist(int data){
        Node temp;
        temp=new Node(data);
        temp.next=this.node;
        this.node=temp;
        return this.node;
    }//初始化链表,建立头结点

    public void addNode(int data){
        Node temp;
        temp=new Node(data);
        temp.next=this.node;
        this.node=temp;
        temp=null;
    }//增添数据,使用从链表头部进行插入

    public int selectNode(int pos){
        Node current;
        int p=0;
        current=this.node;
        while(p<=pos-1&&current!=null){
            current=current.next;
            p++;
        }
        return current.value;
        }//根据输入位置返回指定位置的数据值

    public int deleteNode(){
        Node temp;
        temp=this.node;
        this.node=temp.next;
        return temp.value;
        }//删除节点

    public void printLinklistNode(){
        Node current;
        current=this.node;
        while(current!=null){
            System.out.print(current.value+" ");
            current=current.next;
        }//输出链表数据
    }
}

测试主函数代码

public class testLinklist {

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        LinklistNode head=null;
        head=new LinklistNode();
        head.initLinklist(5);//生成头结点
        for(int i=0;i<5;i++){
            head.addNode(i);//添加节点
        }
        head.printLinklistNode();//输出链表
        System.out.println();
        head.deleteNode();//删除链表节点
        head.printLinklistNode();
        System.out.println();
        head.deleteNode();
        head.printLinklistNode();
        System.out.println();
        System.out.println("pos 2 value:"+head.selectNode(2));//输出指定位置的节点数据值
    }
}

测试效果图示:
这里写图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值