# 1: Single Chain List - 3. Query the last k nodes (O(1))

Producer: TheShyclear

Production time: 2018-7-21

Make it: Find the last kth data in a single-chain list

Version number: 8.0

Defect: Head node can only be inserted once, not Node 1. See Insert function in more detail

Note: Head pointer immutability

Thought: Many problems in single-chain tables require the combination of two pointers, because only the successor nodes can be found in single-chain tables.

When we get to this question, the first reaction must be to point at the head node with a pointer and count the loop to the last node, so that we know the total length of the chain table le, then the last kth node is le+1-k, so the time complexity is O(n).

So do we have a simpler and faster way?Make it O(1)?Certainly.Because of the particularity of single-chain list, it can only represent successor nodes, but not precursor nodes. Usually, we take the method of assistant pointer to solve the corresponding problem.

Code implementation:

```#include<stdio.h>
#include<stdlib.h>
#include<malloc.h>
#include<string.h>

typedef int Elemtype;

typedef struct ListNode
{
Elemtype data;//range
ListNode *m_pNext;//Pointer field
}ListNode,*PListNode;

{
ListNode* p = (ListNode*)malloc(sizeof(ListNode));
if(NULL == p)
{
exit(1);
}
memset(p,0,sizeof(ListNode));
return p;
}

void InitList(PListNode &p)
{
p->m_pNext = NULL;
p->data = 0;
}
int GetLength(PListNode &head)//Problem: head node cannot be manipulated directly
{
int count = 0;
PListNode s = head;
while(s!=NULL)
{
count+=1;
s=s->m_pNext;
}
return count;
}
void InsertList(PListNode &p,Elemtype x,int pos)
{
if(pos<1 || pos>GetLength(p)+1)
{
printf("input pos is error:\n");
exit(1);
}
PListNode s = p;//Head Node s
if(pos == 1)
{
p->data = x;
p->m_pNext = NULL;
}
else
{
while(pos-2)
{
s = s->m_pNext;
--pos;
}//s points to the front
PListNode r =s->m_pNext;

PListNode q = BuyNode();
q->data = x;

s->m_pNext = q;
q->m_pNext = r;
}
}

PListNode Find_Kth_To_Tail(PListNode &p,int k)
{
if(k<1 || k>GetLength(p))
{
printf("input k is error:\n");
exit(1);
}

PListNode s =p;
PListNode q =p;

for(int i=0;i<k-1;++i)
{
s = s->m_pNext;
}
while(s->m_pNext != NULL)
{
s = s->m_pNext;
q = q->m_pNext;
}

return q;
}
{
while(s != NULL)
{
printf("%d ",s->data);
s = s->m_pNext;
}
}
void main()
{
for(int i=1;i<5;++i)
{
}