思路:
这道题很简单,自己首先想到的就是两次循环,一次得到所有的数据,一次获取指定位置;
时间复杂度:O(n)
空间复杂度:O(2)
遇到难点:
A是能A掉,但是空间复杂度过高;可以想到更优的解法
结果:
自己第一个思路想到的
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
class Solution {
public ListNode getKthFromEnd(ListNode head, int k) {
//两边循环直接 求出 第一遍知道长度 第二遍知道从哪个地方取值
if(head==null){
return null;
}
ListNode temp = head;
int count = 1;
while(temp != null){
count++;
temp = temp.next;
}
ListNode tp = head;
//倒数第几个循环得到就行
for(int i = 1;i <= count; i++){
if(count-k == i){
return tp;
}
tp = tp.next;
}
return null;
}
}
之后发现实际上是有规律的:
所以可以使用快慢双指针来进行操作:
public ListNode getKthFromEnd(ListNode head, int k) {
ListNode pre = head;
ListNode behind = head;
while (pre!=null && k >0){
pre = pre.next;
k--;
}
while (pre!=null){
pre = pre.next;
behind = behind.next;
}
return behind;
}
总结:
解题方法都会不一致,要从多个方向进行思考问题。