创建链表
public class ListNode{
public int val;
public ListNode next;
}
ListNode(int x){
val = x;
next = null;
}
//创建
ListNode node1 = new ListNode(1);
遍历链表
public static int getListLength(Node head){
int length = 0;
Node node = head;
while(node != null){
length++;
node = node.next;
}
return length;
}
链表插入
单链表的插入需要考虑三种情况:首部、中部和尾部。
- 在链表的表头插入
newNode.next = head;
head = newNode;
- 在链表的中间插入
newNode.next = node(15).next;
node(15).next = newNode;
- 在链表的结尾插入结点
node(40).next = newNode;
综上所述:链表插入的方法如下所示。
/**
* 链表插入
* @param head 链表头节点
* @param nodeInsert 待插入节点
* @param position 待插入位置,从1开始
* @return 插入后得到的链表头节点
*/
public static Node insertNode(Node head, Node nodeInsert, int position){
if(head == null){
//这里可以认为待插入的结点就是链表的头结点,也可以抛出不能插入的异常
return nodeInsert;
}
//已经存放的元素个数
int size = getSize(head);
if(position > size + 1 || position < 1){
System.out.println("位置参数越界");
return head;
}
//表头插入
if(position == 1){
nodeInsert.next = head;
head = nodeInsert;
return head;
}
Node curNode = head;
int count = 1;
//这里position被上面的size限制住了,不用考虑curNode = null
while(count < position - 1){
curNode = curNode.next;
count++;
}
nodeInsert.next = curNode.next;
curNode.next = nodeInsert;
return head;
}
链表删除
删除操作同样分为在删除头部元素,删除中间元素和删除尾部元素。
- 删除表头结点
head = head.next
- 删除最后一个节点
if(node(7).next == node(40)){
node(7).next = null;
}
- 删除中间节点
cur.next = cur.next.next;
综上所述:链表删除的方法如下所示。
/**
*
* @param head 链表头节点
* @param position 删除节点位置,取值从1开始
* @return 删除后的链表头节点
*/
public static Node deleteNode(Node head, int position){
if(head == null){
return null;
}
int size = getSize(head);
if(position > size || position < 1){
System.out.println("输入的位置参数有误!");
return head;
}
if(position == 1){
return head.next;
}
Node curNode = head;
int count = 1;
while(count < position - 1){
curNode = curNode.next;
count++;
}
curNode.next = curNode.next.next;
return head;
}
后续完善
- 链表单调递增插入。
- 链表单调递增删除。