查找链表中倒数第k(k为正整数)个位置上的结点。若查找成功,算法输出该结点的data值,并返回 1:否则,只返回 0。
点击查看代码
/*************************************************** func name :Find* func function :查找链表中倒数第k(k为正整数)个位置上的结点。若查找成功,算法输出该结点的data值,并返回 1:否则,只返回 0。* func parameter:* @head:链表头结点的地址* @k :要查找的结点(倒数第k个)** return :int* note :None* func author :momolyl@126.com* date :2024/04/22* version :V1.0**************************************************/
typedef int datatype;
typedef struct LkList
{datatype data;struct LkList *next;
} L;
int Find(L *head, int k)
{L *phead = head;int count = 0;while (phead->next) // 遍历链表统计结点的个数count++;if (k > count) // 判断查找的结点是否在合理范围内return 0;L *phead1 = head;L *phead2 = head;for (int i = 0; i < k; i++){phead1 = phead1->next;}while (phead1->next){phead1 = phead1->next;phead2 = phead2->next;}printf("the data of %dTH node from bottom is %d", k, phead2->next->data);return 1;
}