给定一个单向链表(长度未知),请设计一个既节省时间又节省空间的算法来找出该链表中的倒数第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;
}