数据结构--单链表的实现-Java

来源:互联网 发布:积分或换软件 编辑:程序博客网 时间:2024/06/06 10:46
package Linklist;class Node{Node next=null;int data;public Node(int data){this.data=data;}}public class Mylist {//初始化链表Node head=null;//插入数据public void insert(int a) {Node newNode=new Node(a);//空链表直接加在链表头if(head==null){head=newNode;return;}//非空链表先找到最后一个位置Node tmp=head;while(tmp!=null){tmp=tmp.next;}tmp.next=newNode;}//删除数据public Boolean delete(int index){//判断下标是否在链表内部if(index>length()||index<1){return false;}//首位置if (index==1){head=head.next;return true;}//其他位置int i=2;Node preNode=head;Node curNode=head.next;while (curNode!=null) {if(index==i){preNode.next=curNode.next;return true;}preNode=curNode;curNode=curNode.next;i++;}}//统计元素个数public int length(){int len=0;Node tmp=head;while(tmp!=null){tmp=tmp.next;len++;}return len;}}