帶頭單連結清單的頭插,尾插,指定位置插入元素
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;
}