寻找倒数第m个元素

1、题目:
寻找倒数第m个元素
(来自此书:Programming Interviews Exposed Secrets to Landing Your Next Job–程序员面试攻略)

2、算法思路:
两个指针theM,p,初始化为头元素。p指针为遍历指针,theM为位置指针,指向从p指针开始的倒数第m个元素。遍历开始至theM与p相距m个元素后,theM与p开始同步前行。

3、代码:

#include <stdio.h>
#include <stdlib.h>

typedef struct LNode
{
    char value;
    struct LNode *next;
}LNode;

int initLi(LNode **head,LNode **tail)   //尾插法
{
    LNode *th=*tail;
    char c=getchar();
    int flag=1;
    while(c!='$')
    {
        if(c!=' ')
        {
             LNode *temp=malloc(sizeof(LNode));
            if(temp)
            {
                temp->value=c;
                temp->next=NULL;
                if(flag)
                {
                    *head=temp;
                    flag=0;
                }
                else
                {
                    th->next=temp;
                }
                th=temp;
            }
            else
            {
                free(temp);
                return -1;
            }
        }
        c=getchar();
    }
    *tail=th;
    return 0;
}

void visit(LNode **head)
{
    LNode *th=*head;
    for(LNode *p=th;p!=NULL;p=p->next)
    {
        printf("%c->",p->value);
    }
    printf("NULL\n");
}


void delLi(LNode **head)
{

    LNode *th=*head;
    for(LNode *temp=th;temp!=NULL;)
    {
        LNode *p=temp;
        temp=temp->next;
        free(p);
    }
    *head=NULL;
}

/*
*regular
*the last 0 is
*tail
*/
LNode *findLastM(LNode *head,int m)
{
    LNode *theM=head;
    int count=0;
    for(LNode *p=head;p->next!=NULL;p=p->next)
    {
        if(count<m)
        {
            ++count;
        }
        else
        {
            theM=theM->next;
        }
    }
    return theM;
}

int main()
{
    LNode *head=NULL,*tail=NULL;
    if(initLi(&head,&tail))
    {
        printf("error\n");
        return 0;
    }
    printf("LinkedList\n");
    visit(&head);
    printf("The Last %d:\t%c\n",3,findLastM(head,3)->value);
    delLi(&head);
    printf("hello world\n");
    return 0;
}

4、结果:
倒数第3个
倒数第3个

倒数第0个
倒数第0个

5、总结:
A. 寻找倒数第m个元素,要立即与指针关联,指针本来就是指示位置的,不要想着重新建立链表之类,这样耗时耗空间。
B. p->next!=NULL的运用,最后倒数是从p开始的,p最后肯定要指向尾元素!
C. 关于NULL,应该在stdlib.h中有定义了。
D. 尾插法,必须先将尾指针指向具体元素再解引用。


此处主要函数代码情况考虑的不是很完整。

Reference:
http://blog.csdn.net/bestzem/article/details/52104292

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值