1.相关基本操作
public class Mysiglelist {
static class LNode{
int val;
LNode next;
public LNode(int data){
this.val=data;
}
}
public LNode head;
public void addFirst(int data){
LNode node=new LNode(data);
node.next=head;
head=node;
}
public void addLast(int data){
LNode node=new LNode(data);
LNode cur=head;
while(cur.next!=null){
cur=cur.next;
}
cur.next=node;
}
public void show(){
LNode cur=head;
while(cur!=null){
System.err.print(cur.val+" ");
cur=cur.next;
}
System.out.println();
}
public int size(){
LNode cur=head;
int count=0;
while(cur!=null){
count++;
cur=cur.next;
}
return count;
}
public boolean contain(int key){
LNode cur=head;
while (cur.next!=null){
if(cur.val==key){
return true;
}
}
return false;
}
public void addIndex(int data,int index){
if(index-1==0){
addFirst(data);
return;
}
if(index==size()){
addLast(data);
return;
}
if(index<0||index>size()){
return;
}
LNode node=new LNode(data);
LNode fast=head;
LNode slow=head;
while(index-1!=0){
fast=fast.next;
while (index-2!=0){
slow=slow.next;
}
index--;
}
node.next=fast;
slow.next=node;
}
public void delVal(int key){
LNode cur=head;
if(head.val==key){
head=head.next;
}
while (cur!=null){
if(cur.next.next==null&&cur.next.val==key){
cur.next=null;
}
if(cur.val==key){
cur.next=cur.next.next;
}
cur=cur.next;
}
}
public void delFirst(){
head=head.next;
}
public void delLast(){
LNode cur=head;
while(cur.next.next!=null){
cur=cur.next;
}
cur.next=null;
}
public void deliIndex(int index){
if(index==1){
delFirst();
return;
}
if(index==size()){
delLast();
return;
}
LNode fast=head.next;
LNode slow=head;
while(index-1!=0){
fast=fast.next;
while(index-2!=0){
slow=slow.next;
}
index--;
}
slow.next=fast;
}
}
2.操作的调用
public class Test {
public static void main(String[] args) {
Mysiglelist mysiglelist=new Mysiglelist();
mysiglelist.addFirst(1);
mysiglelist.addFirst(2);
mysiglelist.addFirst(3);
mysiglelist.addFirst(4);
mysiglelist.addLast(66666);
mysiglelist.show();
mysiglelist.addIndex(10,1);
mysiglelist.show();
mysiglelist.deliIndex(1);
mysiglelist.deliIndex(2);
mysiglelist.delVal(66666);
mysiglelist.show();
mysiglelist.addIndex(10000,2);
mysiglelist.show();
System.out.println(mysiglelist.contain(4));
}
}