Title description
Input a linked list and output the kth node from the bottom of the linked list.
Example 1
input
1,{1,2,3,4,5}
return value
{5}
method one:
/*
public class ListNode {
int val;
ListNode next = null;
ListNode(int val) {
this.val = val;
}
}*/
public class Solution {
public ListNode FindKthToTail(ListNode head,int k) {
//1.首先定义两个指向链表头的指针p,q;
//2.让p指针先移动到第k节点,然后两个指针同时后移
//3.当p指针为null时,q指向的即为倒数第k个节点。返回q
ListNode p=head, q=head;
while(p != null){
if(k <= 0){
q = q.next;
}
p = p.next;
k--;
}
return k <= 0 ? q : null;
}
}
Method 2: Use Stack, push the node into the stack, and then take out the kth one
public class Solution {
public ListNode FindKthToTail(ListNode head,int k) {
if(head == null || k ==0 ){
return null;
}
//可以先把链表反转,然后找出第k个
Stack<ListNode> stack = new Stack<ListNode>();
int count = 0;
while(head != null){
stack.push(head);
head = head.next;
count++;
}
if(count < k){
return null;
}
ListNode knode = null;
for(int i = 0; i < k; i++){
knode = stack.pop();
}
return knode;
}