java实现链表

来源:互联网 发布:大学生网络暴力事件 编辑:程序博客网 时间:2024/05/14 21:24
public class LinkTest{    public static void main(String args[])    {        Node head=new Node("head");//头节点        Node one=new Node("唐僧");//首节点        Node two=new Node("孙悟空");        Node three=new Node("猪八戒");        Node four=new Node("沙和尚");               Link link=new Link(head);        link.addNode(one);//在尾部添加节点        link.addNode(two);        link.addNode(three);        link.addNode(four);        link.display();//遍历链表        System.out.println("-------------------------添加other");        Node other=new Node("other");        link.insertNode(two,other);//插入一个节点        link.display();        System.out.println("-------------------------删除other");        link.delNode("other");//删除节点        link.display();    }}/** *封装了对节点的一些操作 * */class Link{    private Node head;    public Link(Node head)    {        this.head=head;    }    public void addNode(Node node)    {        Node p=head;        while(true)        {            if(!p.hasNext())            {                p.setNext(node);                break;            }            p=p.getNext();        }    }    //插入节点    public void insertNode(Node p,Node q)    {        q.setNext(p.getNext());        p.setNext(q);    }    //删除节点    public boolean delNode(String nodeName)    {        Node p=head;        if(!p.hasNext())        {            System.out.println("此表为空");            return false;        }        while(p.hasNext())        {            if(p.getNext().getName().equals(nodeName))            {                p.setNext(p.getNext().getNext());                break;            }            p=p.getNext();        }        return true;    }    //遍历链表    public void display()    {        Node p=head.getNext();        while(p.hasNext())        {            System.out.println(p.getName());            p=p.getNext();        }    }}/** *节点封装类 * * */class Node{    private String nodeName;    private Node next;    //用数据域构造一个节点对象    public Node(String nodeName)    {        this.nodeName=nodeName;    }    //返回下一节点的对象    public Node getNext()    {        return this.next;    }    //设置本节点的链域    public void setNext(Node next)    {        this.next=next;    }    //返回节点的数据域    public String getName()    {        return this.nodeName;    }    //判断是否有下一节点    public boolean hasNext()    {        boolean is=false;        if(this.next!=null)        {            is=true;        }        return is;    }}


0 0
原创粉丝点击