带头单链表的头插,尾插,指定位置插入元素
1.头插
分析:
对于还没有进行插入数据的时候,此时的头结点指向头结点自己,这个在初始化里面完成,对于一般情况下的插入,先绑后面再绑前面。具体如下图所示:
程序如下:
public void addFirst(int data) {
Node node=new Node(data);
node.next=this.head.next;
this.head.next=node;
}
二、尾插
分析:如果要进行尾插,那么要先找到尾巴,找到尾巴之后同样的的先绑后面的再绑前面的。对于尾插的先绑后面就是绑头
程序如下:
public void addLast(int data) {
Node cur=this.head;
while(cur.next!=this.head){
cur=cur.next;
}
//循环出来之后cur所指的结点就是尾结点
Node node = new Node(data);
node.next=this.head;
cur.next=node;
}
三、指定位置插入
分析:
1)首先要对要插入的位置进行合法性判断
2)如果下标在其合理范围之内,则接下来要做的事情就是找到要插入位置的前一个结点。之后才能够进行绑定。
程序如下:
public boolean addIndex(int index, int data) {
//1.对index的合法性进行判断
if (index<0||index>getLength()){
throw new UnsupportedOperationException("下标不合法");
}
//2.找到index-1的位置
Node cur=this.head;
for (int i = 0; i < index; i++) {
cur=cur.next;
}
Node node =new Node(data);
//3.进行插入
node.next=cur.next;
cur.next=node;
return true;
}