1、链表的插入操作
头插:链表的头插即将cur.next=head.next;(先将head后的值记录在插入节点的next里);然后head.next=cur; 要注意的是,使用头插方法操作出来的数组,如果你依次插入1 2 3 4 5的话,出来就会是5 4 3 2 1 的逆序。
代码实现
private Entry<T> head;
public Link(){
this.head = new Entry<>(null, null);
}
/**
* 单链表的头插法
* @param val
*/
public void insertHead(T val){
Entry<T> newNode=new Entry<>(val,this.head.next);
this.head.next=newNode;
}
**尾插:**链表的尾插操作出来则与头插操作出来的顺序相反,为正序。 即首先要找到链表的尾部,将next设置成cur后将cur的next设成null即可。
代码实现
public void insertTail(T val){
Entry<T> newNode=new Entry<>(val,null);
Entry<T> cur=head;
while (cur.next!=null){
cur=cur.next;
}
cur.next=newNode;
}
2、链表的逆置
由于前面提到链表的头插操作后会成为逆序,则这里就要应用到链表头插的这一性质。首先我们把head.next直接设为尾部,从head.next.next开始遍历,并且要记录后面的next域的地址值。然后对下面的每个节点进行头插操作。
代码实现
public void reverse(){
Entry<T> cur=this.head.next;
this.head.next=null;
Entry<T> post=null;
while (cur!=null) {
post=cur.next;//记录下一个节点地址,以防链表丢失
cur.next=head.next;//头插
head.next=cur;//头插
cur=post;
}
}