找到⼀个未知长度单链表的倒数第K个节点

转载请注明地址:http://blog.csdn.net/liulongling/article/details/50983318

题目:

找到⼀个未知长度单链表的倒数第K个节点

提示:
head—>1—>2—>3—>4—>5—>6—>7—>8—>9—>10—>NULL.其中倒数第0个节点是NULL,倒数第1个节点是10,倒数第10个节点是1.



如上图可以看出,遍历pPcur的同时将pos--,直到pos等于0时将pPre++,最后发现pCur最后指向空时,pPre指向的位置就是反向pos的位置。


//
//  找到⼀个未知长度单链表的倒数第K个节点.c
//  c++
//
//  Created by 刘龙玲 
//  Copyright © 2016年 liulongling. All rights reserved.
//

#include <stdio.h>

typedef struct Node
{
    int num;
    struct Node* next;
}Node;

Node* listNodeCreat()
{
    Node* head = NULL;
    head =  (Node*)malloc(sizeof(Node*));
    if(head == NULL)
    {
        return NULL;
    }
    
    head->num = -1;
    head->next = NULL;
    
    Node* pCur = head;
    Node* pNew = NULL;
    
    for(int i = 1;i < 11;i++)
    {
        pNew = (Node*)malloc(sizeof(Node*));
        if(pNew == NULL)
        {
            break;
        }
        
        pNew->num = i;
        pNew->next=NULL;
        
        pCur->next = pNew;
        pNew->next=NULL;
        pCur = pNew;
    }
    
    return head;
}

Node* findNodeByK(Node* head,int pos)
{
    Node *pPre = NULL;
    Node *pCur = NULL;
    
    if(head == NULL || pos<=0)
    {
        return NULL;
    }
    
    pPre = head;
    pCur = head;
    
    while(pos > 0)
    {
        pCur = pCur ->next;
        pos--;
        if(pCur == NULL)
        {
            return NULL;
        }
    }
    while(pCur!=NULL)//上图红色区域表示该代码执行的地方
    {
        pCur = pCur->next;
        pPre = pPre->next;
    }
    return pPre;
}

int main()
{
    Node* head  =listNodeCreat();
    for(int i = 0;i < 11;i++)
    {
        Node* node = findNodeByK(head, i);
        if(node!=NULL)
        {
            printf("i= %d num= %d\n",i,node->num);
        }else{
            printf("没有找到%d node\n",i);
        }
    }
    
    return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值