求链表中间节点的值,求链表倒数第K个节点,检测链表的环

int loop(struct Node* head){
    struct Node* p1 = head;
    struct Node* p2 = head;
    int i = 0;
    while(p1 && p2){
        i++;
        if(i!=1){
            if(p1->value == p2->value){
                printf("%d\n",i);
                return 1;
            }    
        }
        p1 = p1->next;
        if(p2->next != null){
            p2 = p2->next->next;    
        }else{
            return 0;
        }
        
    }
    printf("%d\n",i);
    return 0;
}

int middle(struct Node* head){
    struct Node* p1 = head;
    struct Node* p2 = head;
    while(p2){
        p2 = p2->next;
        if(p2 != null){
            p1 = p1->next;
            p2 = p2->next;
        }
    }
    return p1->value;
}

int lastK(struct Node* head,int k){
    struct Node* p1 = head;
    struct Node* p2 = head;
    while(k-->0){
        p2 = p2->next;
    }
    while(p2){
        p1 = p1->next;
        p2 = p2->next;
    }
    return p1->value;
} 
 
 

 

int main(int argc,char *argv[]){
    /**
    struct Node* head = create();
    print(head);
    
    struct Node* x = malloc(sizeof(struct Node));
    x->value = 1;
    delete(x,&head);
    print(head);
    **/
    struct Node* p1 = malloc(sizeof(struct Node));
    p1->value = 1;
    struct Node* p2 = malloc(sizeof(struct Node));
    p2->value = 2;
    struct Node* p3 = malloc(sizeof(struct Node));
    p3->value = 3;
    struct Node* p4 = malloc(sizeof(struct Node));
    p4->value = 4;
    struct Node* p5 = malloc(sizeof(struct Node));
    p5->value = 5;
    p1->next = p2;
    p2->next = p3;
    p3->next = p4;
    p4->next = p5;
    p5->next = null;
    printf("中间节点数值:%d\n",middle(p1));
   printf("倒数第一个节点数值:%d\n",lastK(p1,2));
return 0;    
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值