遍历单链表
- 对于单链表,一定是从头开始逐个往后遍历,所以表头不能丢,不能出现’狗熊掰棒子’问题,丢失了表头的指针
- 代码
public static int getListLength(Node head){
int length = 0;
Node node = head;
while(node != null){
length++;
node = node.next;
}
return length;
}
单链表插入
在单链表的头部插入
头插法的图示
在单链表的中间插入
在单链表的尾部插入
代码构建
public static Node insertNode(Node head,Node insertNode,int position){
if(head.next == null){
head.next = insertNode;
}
int length = getLength(head);
if(position > length + 1 || position < 1){
System.out.println("位置参数越界");
return head;
}
if(position == 1){
insertNode.next = head.next;
head.next = insertNode;
return head;
}
if(position == length + 1){
Node pNode = head;
while(pNode.next != null){
pNode = pNode.next;
}
pNode.next = insertNode;
return head;
}
Node pNode = head;
int count = 1;
while(count < position){
count++;
pNode = pNode.next;
}
insertNode.next = pNode.next;
pNode.next = insertNode;
return head;
}
链表删除
头结点删除
尾结点删除
中间结点删除
代码构建
public static Node deleteNode(Node head,int position){
if(head == null){
return null;
}
int length = getLength(head);
if(position > length || position < 1) {
System.out.println("插入位置有问题");
return head;
}
if(position == 1){
head = head.next;
}else{
Node pNode = head;
int count = 1;
while(count < position - 1){
count++;
pNode = pNode.next;
}
pNode.next = pNode.next.next;
}
return head;
}