当前位置: 代码迷 >> Java相关 >> 用java实现单链表(初学者出征)
  详细解决方案

用java实现单链表(初学者出征)

热度:98   发布时间:2016-04-22 19:11:26.0
用java实现单链表(菜鸟出征)
package code;class Node{    Node next;    int data;    public Node(int data)    {        this.data=data;    }    }class LinkList{    Node first;    //头部    public LinkList()    {        this.first=null;    }    public void addNode(Node no)    {        no.next=first;        first=no;//在头部添加    }    public void delectNode()    {        Node n=first.next;        first=null;        first=n;//在头部删除    }    //删除指定位置    public int Number()    {        int count=1;        //查看有多少元素        Node nd=first;        while(nd.next!=null)        {            nd=nd.next;            count++;        }        return count;    }    public void delectExact(int n)    {        //删除指定位置        if(n>1)        {            int count=1;            Node de=first;            while(count<n-1)            {                de=de.next;                count++;                            }            de.next=de.next.next;        }        else            first=first.next;            }    public void addExact(int n,Node nd)    {        if(n>1)//添加指定位置        {            int count=1;            Node de=first;            while(count<n-1)            {                de=de.next;                count++;                            }            nd.next=de.next;            de.next=nd;        }        else            first=first.next;    }    public int  findNode(int n)    {        int count=1;//查找一个数对应的位置        Node de=first;        while(de.data!=n)        {            de=de.next;            count++;            if(de==null)            {                return -1;            }        }        return count;    }    public void print()    {        Node no=first;//打印所有        while(no!=null)        {            System.out.println(no.data);            no=no.next;        }    }}public class TextNode{    public static void main(String[] args)    {        LinkList ll=new LinkList();        ll.addNode(new Node(12));        ll.addNode(new Node(15));        ll.addNode(new Node(18));        ll.addNode(new Node(19));        ll.addNode(new Node(20));        /*System.out.println(ll.first.data);        ll.delectNode();        System.out.println(ll.first.data);*/        System.out.println(ll.Number());        ll.delectExact(3);        ll.addExact(3, new Node(100));        System.out.println(ll.Number());//        ll.print();        System.out.println(ll.findNode(112));            }}

大一菜鸟初学,有误之处请谅解。

1楼V辽仇杀队
好赞!
  相关解决方案