第一种就是用正常思想,倒数第K个,就是正数第N-K个;
第二种用了快慢指针,快指针先走差值K,等快指针为空了,慢指针正好到了我们要找到的倒数第K个结点;
第三种是自己设计了栈,都入栈后,倒数第K个,出栈的时候就是正数了
void Print_Last_KA(LinkList* plist, int k)
{
assert(plist != nullptr);
if (k<1 || k>plist->cursize) exit(1);
ListNode* p = plist->head->next;
int len = plist->cursize - k;
for (int i = 0; i < len; ++i)
{
p = p->next;
}
printf("%d\n", p->data);
}
void Print_Last_KB(LinkList* plist, int k)
{
assert(plist != nullptr);
if (k < 1) exit(1);
ListNode* p = plist->head->next;
ListNode* cur = plist->head->next;
while (p != nullptr && k--)
{
p = p->next;
}
if (NULL == p) exit(2);
while (p != nullptr)
{
p = p->next;
cur = cur->next;
}
printf("%2d\n", cur->data);
}
void Print_Last_KC(LinkList* plist, int k)
{
assert(plist != nullptr);
if (k < 1) exit(1);
int n = 0;
ListNode* p = plist->head->next;
while (p != nullptr)
{
++n;
p = p->next;
}
if (n < k) exit(2);
p = plist->head->next;
int* stack = (int*)malloc(sizeof(int) * n);
if (nullptr == stack) exit(3);
int top = 0;
while (p != nullptr)
{
stack[top] = p->data;
top++;
p = p->next;
}
p = plist->head->next;
while (k--)
{
top--;
}
printf("%d", stack[top]);
}