題解 | #鏈表中倒數(shù)最后k個結(jié)點 01#
鏈表中倒數(shù)最后k個結(jié)點
http://www.fangfengwang8.cn/practice/886370fe658f41b498d40fb34ae76ff9
import java.util.Stack; public class Solution { /** * 代碼中的類名、方法名、參數(shù)名已經(jīng)指定,請勿修改,直接返回方法規(guī)定的值即可 * * * @param pHead ListNode類 * @param k int整型 * @return ListNode類 */ public ListNode FindKthToTail (ListNode pHead, int k) { // write code here if (pHead == null || k == 0){ return null; } Stack<ListNode> stack = new Stack<>(); //鏈表節(jié)點壓棧 while (pHead != null) { stack.push(pHead); pHead = pHead.next; } // 判斷棧的元素是否小于k if (stack.size() < k){ return null; } //在出棧串成新的鏈表 ListNode firstNode = stack.pop(); while (--k > 0) { // 將出棧的元素重新連接成為鏈表 ListNode temp = stack.pop(); temp.next = firstNode; firstNode = temp; } return firstNode; } }