给定一个单向链表(长度未知),请设计一个既节省时间又节省空间的算法来找出该链表中的倒数第m个元素。实现这个算法,并为可能出现的特例情况安排好处理措施。“倒数第m个元素”是这样规定的:当m=0时,链表的

给定一个单向链表(长度未知),请设计一个既节省时间又节省空间的算法来找出该链表中的倒数第m个元素。实现这个算法,并为可能出现的特例情况安排好处理措施。“倒数第m个元素”是这样规定的:当m=0时,链表的最后一个元素将被返回

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

struct listElementType
{
    int data;
    listElementType* next;

};

typedef struct listElementType* m_list;

m_list find_the_mth_element_from_end(m_list u_list,int m)
{
    m_list p1 = NULL,p2 = NULL;

    p1 = u_list;
    for (int i = 0; i < m; i++)
    {
        if (p1->next)
        {
            p1 = p1->next;
        }
        else
        {
            return NULL;
        }
    }

    p2 = u_list;
    while (p1->next)
    {
        p1 = p1->next;
        p2 = p2->next;
    }
    return p2;
}

m_list createList(const int& u_listLength)
{
    int i = 0,a = 0;
    m_list head = NULL,p1 = NULL,tail = NULL;
    for(i = 1; i <= u_listLength; i++)
    {
        p1 = (m_list)malloc(sizeof(m_list));
        if (p1 != NULL)
        {
            printf("input the %d th number of list:",i);
            scanf("%d",&a);
            p1->data = a;
            if (head == NULL)
            {
                head = p1;
                tail = p1;
            }
            else
            {
                tail->next = p1;
                tail = p1;
            }
            tail->next = NULL;
        }
        else
        {
            printf("i:%d,p1 malloc error\n",i);
        }
    }
    return head;
}

void freeList(m_list u_list)
{
    m_list head,listTmp;
    head = u_list;
    while (head != NULL)
    {
        listTmp = head;
        head = head->next;
        free(listTmp);
        listTmp = NULL;
    }
    listTmp = NULL;

}

void printList(m_list q)
{
    while (q)
    {
        printf("%d ",q->data);
        q = q->next;
    }
    printf("\n");
}

int main(void)
{
    m_list u_list = NULL;
    int u_listLength = 0;
    int u_dstNodePosition = 0;
    printf("input the listLength:");
    scanf("%d",&u_listLength);
    u_list = createList(u_listLength);
    if (u_list != NULL)
    {
        printList(u_list);
        printf("input the dstNodePosition:");
        scanf("%d",&u_dstNodePosition);
        m_list u_destNode = find_the_mth_element_from_end(u_list,u_dstNodePosition);
        if (u_destNode)
        {
            printf("dstNodeData:%d\n",u_destNode->data);
        }
        else
        {
            printf("u_dstNodePosition:%d get no Node\n",u_dstNodePosition);
        }
        freeList(u_list);
    }
    else
    {
        printf("list malloc error\n");
        return -1;
    }
    return 0;
}



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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值