题目:
解决方法:双指针、栈、递归
1.双指针
public ListNode FindKthToTail (ListNode pHead, int k) {
// write code here
ListNode slow = pHead;
ListNode fast = pHead;
while(k>0&&fast!=null){
fast = fast.next;
k--;
}
if(k>0)
return null;
while(fast!=null)
{
fast = fast.next;
slow = slow.next;
}
return slow;
}
时间复杂度:O(n)
空间复杂度:O(1)
2.栈
public ListNode FindKthToTail (ListNode pHead, int k) {
// write code here
Stack<ListNode> stack = new Stack<>();
while(pHead!=null){
stack.push(pHead);
pHead = pHead.next;
}
ListNode p = null;
while(k>0&&!stack.empty()){
p = stack.pop();
k--;
}
if(k==0)
return p;
return null;
}
时间复杂度:O(n)
空间复杂度:O(n)
3.递归
static int cnt = 0;
public ListNode FindKthToTail (ListNode pHead, int k) {
// write code here
if(pHead==null)
return null;
ListNode p = FindKthToTail(pHead.next,k);
cnt++;
if(cnt<k)
return null;
else if(cnt==k)
return pHead;
else
return p;
}
时间复杂度O(n2)
空间复杂度O(1)