单向链表
单向链表节点的定义
public class Node {
public int val;
public Node next;
public Node(int val){
this.val=val;
next=null;
}
}
1.JAVA如何构造单向链表
一般Node定义一个节点,一个节点有一个值val,一个指向下一个节点的指针next
构建链表:Node的指针next指向下一个Node
2.如何获取链表的长度
public int getLengthNode(Node head){
int count =0;
Node node = head;//头节点head
while (node!=null){
count++;
node=node.next;
}
return count;
}
3.链表的插入
public static Node insertNode(Node head,Node nodeInsert,int position){
//nodeInsert是头节点,无法进行插入
if (head==null){
return nodeInsert;
}
//获取链表的存放节点数
int size = getLengthNode(head);
//判断参数是否合法
if (position<1 || position >size +1){
return head;
}
//头节点插入
if (position==1){
head=nodeInsert;
return head;
}
//除头结点插入的其他情况
Node pNode=head;
int count = 1 ;
while (count < position -1){
count++;
pNode=pNode.next;
}
//坑
nodeInsert.next=pNode.next;
pNode.next=nodeInsert;
return head;
}
4.链表的删除
/**
* 删除链表中的元素
* @param head 链表
* @param position 要删除的节点位置
* @return 删除后的新链表
*/
public Node deleteNode(Node head,int position){
if (head==null){
return null;
}
int size = getLengthNode(head);
if (position<1 || position >size){
System.out.println("参数不合法");
return head;
}
//删除表头节点
if (position == 1){
head=head.next;
return head;
}else {
Node preNode = head;
int count = 1;
while (count<position-1){
preNode=preNode.next;
count++;
}
//curNode要删除的节点
Node curNode=preNode.next;
preNode.next=curNode.next;
}
return head;
}