先创建节点类:
class ListNode{
public int data;
ListNode next;
public ListNode(int data) {
this.data = data;
this.next=null;
}
}
所有以下方法都在MySignalList类中,并且在此类中定义头部:
class MySignalList {
public ListNode head;
public MySignalList() {
this.head = null;
}
}
//头插法
public void addFirst(int data){
ListNode node = new ListNode(data);
if(this.head==null){
this.head=node;
}else{
node.next=this.head;
this.head=node;
}
}
//尾插法
public void addLast(int data){
ListNode node=new ListNode(data);
ListNode cur=this.head;
if(this.head==null){
this.head=node;
}else{
while(cur.next!=null){
cur=cur.next;
}
cur.next=node;
}
}
// 查找是否包含关键字key是否在单链表当中
public boolean contains(int key){
ListNode cur =this.head;
while(cur!=null){
if(cur.data==key){
return true;
}
cur=cur.next;
}
return false;
}
//求单链表的长度
public int getLength(){
ListNode cur =this.head;
int count=0;
while(cur!=null){
count++;
cur=cur.next;
}
return count;
}
// 任意位置插入,第一个数据节点为0号下标
public ListNode searchIndex(int index){
ListNode cur=this.head;
int count=0;
while(count<index-1){
count++;
cur=cur.next;
}
return cur ;
}
public boolean addIndex(int index,int data){
if(index<0|index>getLength()){
System.out.println("插入不合法");
return false;
}
if(index==0){
addFirst(data);
return true;
}
ListNode cur= searchIndex(index);
ListNode node = new ListNode(data);
node.next=cur.next;
cur.next=node;
cur=node;
return true;
}
//删除第一次出现关键字为key的节点
private ListNode searchPre(int key){
ListNode pre=this.head;
while (pre.next!=null){
if(pre.next.data==key){
return pre;
}
pre=pre.next;
}
return null;
}
public void remove(int key){
if(this.head==null){
System.out.println("单链表为空");
return;
}
if(this.head.data==key) {
this.head = this.head.next;
}
ListNode pre=searchPre(key);
if(pre==null){
return;
}
pre.next=pre.next.next;
}
// 删除所有值为key的节点
public void removeAllKey(int key){
if(this.head==null){
System.out.println("单链表为空");
return;
}
if(this.head.data==key){
this.head=this.head.next;
}
ListNode pre=this.head;
ListNode cur=this.head.next;
while(cur!=null){
if(pre.next.data==key){
pre.next=cur.next;
cur=cur.next;
}else{
pre=cur;
cur=cur.next;
}
}
}
//打印单链表
//打印
public void display(){
ListNode cur =this.head;
while(cur!=null){
System.out.print(cur.data+" ");
cur=cur.next;
}
System.out.println();
}