//节点
class Node{
public int value;
public Node next;
public Node(int value){
this.value=value;
}
}
public class SingleLinkedList {
//头节点
public Node head;
public int usedsize;
//穷举法创造一个单链表
public void createList(){
Node node1=new Node(1);
Node node2=new Node(2);
Node node3=new Node(3);
Node node4=new Node(4);
Node node5=new Node(5);
node1.next=node2;
node2.next=node3;
node3.next=node4;
node4.next=node5;
node5.next=null;
this.head=node1;
this.usedsize=5;
}
//头插法
public void addFirst(int data){
Node node=new Node(data);
if(head==null){
head=node;
}
else{
node.next=head;
head=node;
}
this.usedsize++;
}
//尾插法
public void addLast(int data){
Node node=new Node(data);
if(head==null){
head=node;
}
else{
Node cur=head;
while(cur.next!=null){
cur=cur.next;
}
cur.next=node;
}
this.usedsize++;
};
//任意位置插入,第一个数据节点为0号下标
public void addIndex(int index,int data){
Node node=new Node(data);
if(index<0||index>this.usedsize){
throw new RuntimeException("index不合法!");
}
if (index==0){
addFirst(data);
return;
}
if (index==this.usedsize){
addLast(data);
return;
}
else{
Node cur=head;
while ((--index)!=0){
cur=cur.next;
}
node.next=cur.next;
cur.next=node;
}
usedsize++;
}
//查找是否包含关键字key是否在单链表当中
public boolean contains(int key){
Node cur=head;
while(cur!=null){
if (cur.value==key){
return true;
}
}
return false;
};
//删除第一次出现关键字为key的节点
public void remove(int key){
if (this.head==null){
return;
}
if (this.head.value==key){
head=head.next;
usedsize--;
return;
}
Node prev=findPrev(key);
if(prev==null){
throw new RuntimeException("不存在;");
}
Node del=prev.next;
prev.next=del.next;
usedsize--;
}
//删除所有值为key的节点
public void removeAllKey(int key){
if (this.head==null){
return;
}
Node cur=head.next;
Node prev=head;
while(cur!=null){
if(cur.value==key){
prev.next=cur.next;
cur=cur.next;
usedsize--;
}
else{
prev=cur;
cur=cur.next;
}
}
if (this.head.value==key){
head=head.next;
usedsize--;
return;
}
};
//得到单链表的长度 直接return usdsize
public int size(){
//方法一
//return usedsize;
int count = 0;
Node cur =head;
while(cur!=null){
count++;
cur=cur.next;
}
return count;
}
//print 链表
public void mytoString(){
Node cur =head;
while(cur!=null){
System.out.print(cur.value+" ");
cur=cur.next;
}
}
//找到关键字key的前一节点
private Node findPrev(int key){
Node prev=head;
while (prev.next!=null){
if(prev.next.value==key){
return prev;
}
prev=prev.next;
}
return null;
}
public void clear(){
Node cur=head;
while(cur!=null){
Node CurNext=cur.next;
cur.next=null;
cur=CurNext;
}
head=null;
usedsize=0;
}
public void clear1(){
this.head=null;
this.usedsize=0;
}
}
模拟单链表的实现(JAVA)
最新推荐文章于 2022-12-17 12:51:58 发布