1、头插
如果原链表不为空,要插入的节点的下一个节点就是原来链表的头节点,新链表的头节点就是要插入的节点;
如果原链表为空,直接插入,头节点就是要插入的节点
public void pushFront(Node node){
if(head!=null) {
node.next = this.head;
this.head=node;
}else {
this.head=node;
}
}
2、尾插
如果 原链表为空,尾插同头插
如果原链表不为空,找到链表最后一个结点,最后一个结点的下一个结点就是要插入的结点
//查找链表最后一个节点,前提是链表中至少有一个节点
private Node curlast(){
if(this.head==null){
throw new Error();
}
Node cur = this.head;
while(cur.next != null) {
cur = cur.next;
}
return cur;
}
//尾插
public void pushBack(Node node){
if(this.head==null){
this.head=node;
}else {
Node node1 = curlast();
node1.next = node;
}
}
3、头删
如果原链表不为空,头删就是让原链表的头结点的下一个节点为新链表的头结点
public void popFront(){
if(this.head == null){
throw new Error();
}else{
this.head = this.head.next;
}
}
4、尾删
如果原链表不为空,尾删就是让原链表的倒数第二个结点的下一个节点为空
//找倒数第二个节点
private Node curLastLast(){
Node cur1 = null;
while(cur1.next.next != null ){
cur1 = cur1.next;
}
return cur1;
}
//尾删
public void popBack(){
if(this.head == null){
throw new Error();
}else {
Node node2 = curLastLast();
node2.next = null;
}
}
5、打印链表
public void display(){
//如何通过循环,遍历链表的每一个节点
Node cur = this.head;
while (cur !=null) {
System.out.println(cur.value);
cur=cur.next;
}
}