2009 查找链表倒数第k个位置上的节点

思想:定义两个指针变量p,q,初始时均指向头节点的下一个节点,p指针沿着链表移动,当p指针移动到第k节点时,q与p同步移动,当p移动到最后一个节点时q为所求节点

代码:

typedef struct LNode{
    int data;
    struct LNode *next;
    
}*LinkList;
int search_k(LinkList list,int k)
{
    LinkList p=list->next,q=list->next;
    int count=0;
    while(p!=null)
    {
        if(count<k)count++;
        else q=q->next;p=p->next;
    }
    if(count<k)
    {
        return 0;
    }
    else{
        printf("%d",q->data);
        return 1;
    }
}

猜你喜欢

转载自www.cnblogs.com/yangmenda/p/11707944.html