首页 > 解决方案 > 没有 p=p->link 的链表箭头运算符循环

问题描述

如何使用多个箭头运算符(->)到达具有 x 个节点的链表的最后一个节点?

我很好奇如何在我的代码中表达 -> 操作 x 次

伪代码 p (->next)*x

我想做 p->link->link->..... 我想做 x 次而不使用 p=p->link

标签: cloopslinked-listoperator-keyword

解决方案


你可以使用递归:

struct List
{
    struct List *next;
};


struct List *findLast(struct List *node)
{
    if(node -> next) return findLast(node -> next);
    return node;
}

struct List *findNth(struct List *node, size_t N)
{
    if(N && node -> next) return findLast(node -> next, N - 1)
    if(!N) return node;
    return NULL;
}

推荐阅读