创建链表
在LeeCode中一般这样创建链表
public class ListNode{
public int data;
public ListNode next;
public ListNode(int data){
this.data = data;
next = null;
}
}
遍历链表
要注意创建一个变量来遍历,不要把head丢掉了文章来源:https://www.toymoban.com/news/detail-610521.html
public static int getListLength(ListNode head){
int len = 0;
ListNode cur = head;
while(cur != null){
len++;
cur = cur.next;
}
return len;
}
插入链表节点
count < position - 1可以方便操作,还能防止下标越界(cur为null)文章来源地址https://www.toymoban.com/news/detail-610521.html
public static ListNode insertNode(ListNode head, ListNode newNode, int position){
if(head == null){
return newNode;
}
//越界判断
int size = getLength(head);
if(position > size + 1 || position < 1){
System.out.println("位置参数越界");
return head;
}
//表头插入
if(position == 1){
newNode.next = head;
head = newNode;
return head;
}
//表中插入&表尾插入
ListNode cur = head;
int count = 1;
while(count < position - 1){
cur = cur.next;
count++;
}
newNode.next = cur.next;
cur.next = newNode;
return head;
}
删除链表节点
public static ListNode deleteNode(ListNode head, int position){
if(head == null){
return null;
}
//越界判断
int size = getLength(head);
//注意position > size与插入链表节点有所区别
if(position > size || position < 1){
System.out.println("位置参数越界");
return head;
}
//表头删除
if(position == 1){
return head.next;
}
//表中删除&表尾删除
ListNode cur = head;
int count = 1;
while(count < position - 1){
cur = cur.next;
count++;
}
cur.next = cur.next.next;
return head;
}
到了这里,关于算法通关村第一关——链表青铜挑战笔记(单链表)的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!