在创建一个链表之前,我们先传建一个接口,如图所示:
点击OK,这时我们已经创建好了一个接口,我们要在接口中写链表的一些方法:
此时,我们应该创建一个类,来继承这个接口,在类中重写这些函数:
这时我们把鼠标放在波浪线上点击alt加enter进行重写这些函数。
链表是有节点组成,每个节点上有data和next。首先我们需要定义这些:
1.头插法:
我们先定义一个节点,判断链表是否为空,若为空,此节点就为头结点,否则让此节点的next等于原链表的头结点,头结点等于此节点。
2.尾插法
我们先定义一个节点,判断链表是否为空,若为空,此节点就为头结点,也是为节点。否则,我们再定义一个节点,用它来遍历链表找到链表的尾节点,让尾节点的next为此节点。
3.任意位置插入,第一个数据节点为0号下标
public boolean addIndex(int index, int data) {
if (index == 0) {
addFirst (data) ;
return true;
}
Node node=new Node(data);
Node cur=searchIndex(index);
return false;
}
private void checkIndex(int index){
if(index0){
}
}
private Node searchIndex(int index){
Node cur=this.head;
int count=0;
while(count<index-1){
cur=cur.next;
count++;
}
return cur;
}
4.查找是否包含关键字key是否在单链表当中
public boolean contains(int key) {
Node cur=this.head;
while(cur!=null){
if(cur.datakey){
return true;
}
cur=cur.next;
}
return false;
}
5.删除第一次出现关键字为key的节点
private Node searchPre(int key){
Node pre=this.head;
if(pre.datakey){
return this.head;
}
while(pre.next!=null){
if(pre.next.datakey){
return pre;
}
pre=pre.next;
}
return null;
}
@Override
public int remove(int key) {
int oldData=0;
Node pre=searchPre(key);
if(pre==null){
throw new UnsupportedOperationException("不存在key");
}
//是头结点的时候
if(pre==head&&pre.data==key){
oldData=this.head.data;
this.head=this.head.next;
return oldData;
}
Node del=pre.next;
oldData=del.data;
pre.next=del.next;
return oldData;
}
6.删除所有值为key的节点
public void removeAllKey(int key) {
if(this.head==null){
return;
}
Node pre=this.head;
Node cur=pre.next;
while(cur!=null){
if(cur.data==key){
cur=cur.next;
}
pre.next=cur;
cur=cur.next;
}
if(head.data==key){
head=this.head.next;
}
}
7.得到单链表的长度
public int getLength() {
int count=0;
Node cur=this.head;
while(cur!=null){
count++;
}
//write
return 0;
}