# 题目
实现一种算法,找出单向链表中倒数第 k 个节点。返回该节点的值。
示例 1:
输入: 1->2->3->4->5 和 k = 2 | |
输出: 4 |
tips:
- 给定的 k 保证是有效的。
# 解法一:使用栈
利用栈先进后出的特点。
/** | |
* Definition for singly-linked list. | |
* public class ListNode { | |
* int val; | |
* ListNode next; | |
* ListNode(int x) { val = x; } | |
* } | |
*/ | |
class Solution { | |
public int kthToLast(ListNode head, int k) { | |
Stack<Integer> stack = new Stack(); | |
ListNode cur = head; | |
while(cur != null){ | |
stack.add(cur.val); | |
cur =cur.next; | |
} | |
int index = 1; | |
while(index > 0){ | |
if(k == index++){ | |
return stack.pop(); | |
} | |
stack.pop(); | |
} | |
return 0; | |
} | |
} |
# 解法二:快慢指针
/** | |
* Definition for singly-linked list. | |
* public class ListNode { | |
* int val; | |
* ListNode next; | |
* ListNode(int x) { val = x; } | |
* } | |
*/ | |
class Solution { | |
public int kthToLast(ListNode head, int k) { | |
ListNode fast = head; | |
for (int i = 0; i < k; i++) { | |
fast = fast.next; | |
} | |
ListNode slow = head; | |
while (fast != null) { | |
slow = slow.next; | |
fast = fast.next; | |
} | |
return slow.val; | |
} | |
} |