class Node{
public int val;
public Node next ;
public Node(int val){
this.val=val;
}
}
public class SingleLinkedList {//单链表
public Node head=null;
public int usedSize=0;
public void myToString(){//打印
Node cur=this.head;
while(cur!=null){
System.out.print(cur.val+" ");
cur=cur.next;
}
}
public boolean contains(int key){//是否存在关键字key
Node cur=this.head;
while(cur!=null){
if(cur.val==key){
return true;
}
cur=cur.next;
}
return false;
}
public int size(){//求长度
return usedSize;
}
public int size1(){
Node cur=this.head;
int count=0;
while(cur!=null){
count++;
cur=cur.next;
}
return count;
}
public void addFirst(int val){//头插法
Node node=new Node(val);
if(this.head==null){
this.head=node;
}
else {
node.next = head;
this.head = node;
}
this.usedSize++;
}
public void addLast(int val){//尾插法
Node node=new Node(val);
if(this.head==null){
this.head=node;
}
else{
Node cur=this.head;
while(cur.next!=null){
cur=cur.next;
}
cur.next=node;
}
usedSize++;
}
public void addIndex(int index,int val){//在index位置插
Node node=new Node(val);
if(index==0){
addFirst(val);
}
else if(index==usedSize){
addLast(val);
}
else if(index<0||index>usedSize){
return;
}
else
{
Node cur = this.head;
for (int i = 0; i < index - 1; i++) {
cur = cur.next;
}
node.next=cur.next;
cur.next=node;
usedSize++;
}
}
public void remove(int key){
if(head==null){//删除第一个key
return;
}
if(head.val==key){
this.head=head.next;
usedSize--;
return;
}
Node cur= this.prev(key);
if(cur==null){
System.out.println("没找到");
return;
}
cur.next=cur.next.next;
this.usedSize--;
}
public Node prev(int key){//查找key的前驱
Node cur=this.head;
while(cur.next!=null){
if(cur.next.val==key){
return cur;
}
cur=cur.next;
}
return null;
}
public void allRemove(int key){
if(this.head==null){//key全部删除
return;
}
Node prev=this.head;
Node cur=this.head.next;
while(cur!=null){
if(cur.val==key){
prev.next=cur.next;
cur=cur.next;
this.usedSize--;
}
else{
prev=cur;
cur=cur.next;
}
}
if(this.head.val==key){
this.head=head.next;
this.usedSize--;
}
}
}
java 单链表无头不循环的实现
最新推荐文章于 2024-05-21 22:13:42 发布