求倒数第几个
将链表节点数求出,再减去K即可
/**
- Definition for singly-linked list.
- struct ListNode {
-
int val;
-
ListNode *next;
-
ListNode(int x) : val(x), next(NULL) {}
- };
/
class Solution {
public:
int kthToLast(ListNode head, int k)
{
int size = 0;
ListNode *tem = head;
while (tem!=NULL)
{
size++;
tem = tem->next;
}
for (int i = 0; i < (size - k); i++)
{
head = head->next;
}
return head->val;
}
};