Path: with two pointers, p1 and p2, p1 first K-1 step, p2 points to the header node, and then the two go together, when p1 points to the end node, p2 points to the last k nodes. P1 took the K-1 step, pointing to the k node of the positive number, when the end of the node when p1 took the n-k step, then p2 to the n-k + 1 node, is the last k node. The Code is as follows:
[Cpp] <SPAN style = "FONT-SIZE: 14px"> node * find (node * list, int k)
{
Node * p1 = list;
Node * p2 = list;
For (int I = 0; I <K-1; I ++)
{
P1 = p1-> next;
}
While (p1-> next! = NULL)
{
P1 = p1-> next;
P2 = p2-> next;
}
Return p2;
}
</SPAN>
Node * find (node * list, int k)
{
Node * p1 = list;
Node * p2 = list;
For (int I = 0; I <K-1; I ++)
{
P1 = p1-> next;
}
While (p1-> next! = NULL)
{
P1 = p1-> next;
P2 = p2-> next;
}
Return p2;
}
Problems:
1. What should the program do when the length of the linked list is smaller than k?
2. What should the program do when the input linked list pointer parameter is a null pointer?
3. How to Handle k = 0
Case 1: You need to add a judgment. If k is greater than the length of the linked list, return NULL
Case 2: returnNULL when the pointer is null
Case 3: When k = 0, the system returns the last 0th nodes, and only the first node does not have the last 0th nodes. At this time, the system returns NULL;
The modified program is as follows:
[Cpp] <SPAN style = "FONT-SIZE: 14px"> node * find (node * list, intk)
{
Int length = 0;
Node * p = list;
While (p! = NULL)
{
Length ++;
P = p-> next;
}
If (list = NULL | k = 0 | k> length)
{
Return NULL;
}
Node * p1 = list;
Node * p2 = list;
For (int I = 0; I <K-1; I ++)
{
P1 = p1-> next;
}
While (p1-> next! = NULL)
{
P1 = p1-> next;
P2 = p2-> next;
}
Return p2;
}
</SPAN>
Node * find (node * list, intk)
{
Int length = 0;
Node * p = list;
While (p! = NULL)
{
Length ++;
P = p-> next;
}
If (list = NULL | k = 0 | k> length)
{
Return NULL;
}
Node * p1 = list;
Node * p2 = list;
For (int I = 0; I <K-1; I ++)
{
P1 = p1-> next;
}
While (p1-> next! = NULL)
{
P1 = p1-> next;
P2 = p2-> next;
}
Return p2;
}