//获取单链表有效结点个数标签:head,单链,ListNode,cur,temp,next,题目,null From: https://www.cnblogs.com/bbnltxdy/p/17675526.html
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());
}
}