//获取单链表有效结点个数
public static int getLength(ListNode head){
if(head.next == null){
return 0;
}
int result = 0;
ListNode temp = head.next;
while (temp != null){
result ++;
temp = temp.next;
}
return result;
}
//查找单链表的倒数第k个结点
public static ListNode getLastK(int k, ListNode head){
if(head.next == null){
System.out.println("空链表...");
return null;
}
int length = getLength(head);
//校验 再遍历size-k个
if(k<0 || k>length){
return null;
}
ListNode temp = head.next;
int result = 0;
while (result == (length-k)){
result ++;
temp = temp.next;
}
return temp;
}
//反转链表
public static void reverseList(ListNode head){
if(head.next == null || head.next.next == null){
System.out.println("空链表...");
return;
}
ListNode pre = null;
ListNode temp = null;
ListNode cur = head;
while (cur != null) {
temp = cur.next;
cur.next = pre;
pre = cur;
cur = temp;
}
}
//从尾到头打印单链表
public static void printFromTail(ListNode head){
if(head.next == null){
return;
}
Stack<ListNode> stack = new Stack<>();
ListNode cur = head.next;
while (cur != null){
stack.push(cur);
cur = cur.next;
}
while (stack.size() > 0) {
System.out.println(stack.pop());
}
}
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· DeepSeek 开源周回顾「GitHub 热点速览」
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· AI与.NET技术实操系列(二):开始使用ML.NET
· 单线程的Redis速度为什么快?