估计这个问题在面试中被问烂了。
思路是先找到正数的第K个结点的指针pT,然后和指向头结点的指针pN一起向后移动,直到第K个指针指向NULL,此时pN指向的结点即倒数第K个结点。
如图:
#include <stdio.h>
#include <time.h>
#include <stdlib.h>
typedef struct Node
{
int data;
Node* next;
}Node, *List; List createList(int num) //随机生成数字,构造链表
{
List aList = (List)malloc(sizeof(Node));
aList->next = NULL;
aList->data = ;
Node* qT = aList; for ( int i=; i< num; ++i)
{
Node* pTN = (Node*)malloc(sizeof(Node));
pTN->data = rand()%;
pTN->next = NULL;
qT->next = pTN;
qT = pTN;
}
return aList;
} void printList(List aList) //正序打印链表
{
if ( aList == NULL || aList->next == NULL )
return; Node* pT = aList->next;
printf("element of the list:\n\t");
while( pT != NULL )
{
printf("%d ", pT->data);
pT = pT->next;
} printf("\n");
} //链表倒数第K个节点主算法
Node* rfind_K_node(List aList, int K)
{
if ( aList == NULL || K <= )
return NULL; Node* pT = aList;
Node* pN = aList;
for ( int i=; i< K; ++i )
{
pT = pT->next;
} while ( pT != NULL )
{
pN = pN->next;
pT = pT->next;
} return pN;
} void deleteList(List aList) //删除链表
{} int main(int argc, char const *argv[])
{
srand((int)time());
List aList = createList();
printList(aList);
printf("The bottom %d Node data is %d\n", , rfind_K_node(aList, )->data);
deleteList(aList); return ;
}