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

xiaoxiao2021-02-28  97

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; } }
转载请注明原文地址: https://www.6miu.com/read-30306.html

最新回复(0)