classSolution{ publicintkthToLast(ListNode head, int k){ ListNode first = head; ListNode second = head; while(k-- >0){ first = first.next; } while(first!=null){ first = first.next; second = second.next; } return second.val; }
####题解二:使用栈求解(一看到倒数某某元素,要先想到栈)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
classSolution{ publicintkthTolast(ListNode head , int k){ Stack<ListNode> stack = new stack<>(); //链表结点压栈处理 while(head!=null){ stack.push(head); head = head.next; } //出栈串成新的链表 ListNode firstnode = stack.pop(); while(--k>0){ ListNode temp = stack.pop(); temp.next = firstNode; //这一步是不必要的,除非要求返回最后一个到倒数第k个结点链表,需要从新连接构建 firstNode = temp; } return firstnode.val; } }