请教一个看似简单的递归问题

hab1980 2004-05-11 10:48:08
要求:使用递归(即不要使用栈(因为用栈太简单))
问题:有一个单向链表SLL,其存储结构如下所示
head node -> node 1 -> node 2 -> ... -> tail node -> NULL
已知有一个节点指针iter指向SLL中的某个节点,求iter前第M个节点的指针?(如:若iter指向node 10,M = 2,则求解node 8的指针)
我的思路:从head node开始通过递归往后搜索,找到与iter匹配的节点后,递归返回M次就得到解答。(用栈很简单,不断压栈,找到匹配后,弹出M次就得到解答,然后把栈清空,搞定)
...全文
31 2 打赏 收藏 转发到动态 举报
写回复
用AI写文章
2 条回复
切换为时间正序
请发表友善的回复…
发表回复
hab1980 2004-05-13
  • 打赏
  • 举报
回复
SSL * FindPreItem(SSL * head, SSL * curr, int M)
{
static int counter = 0;
static SSL * res = 0;
if( head != curr )
FindPreItem(head->next , curr, M);

if(counter == M)
res = head;
counter++;
return res;
}

good! 可以再简化一点的,因为curr和M在递归调用过程中没有变化,所以可以放在外面,减少栈操作量,还有返回值也可以定义在外部,因为只执行了一次: if (counter == M) res = head;
  • 打赏
  • 举报
回复
#include <stdio.h>
#include <stdlib.h>


struct SSL
{
struct SSL * next;
};

SSL * FindPreItem(SSL * head, SSL * curr, int M)
{
static int counter = 0;
static SSL * res = 0;
if( head != curr )
FindPreItem(head->next , curr, M);

if(counter == M)
res = head;
counter++;
return res;
}


int main()
{
SSL *head = 0, *iter = 0;
int i = 0;
head = (SSL *)malloc(sizeof(SSL));printf("%p\n", head);
for( i = 0, iter = head; i < 9; i++)
{
iter->next = (SSL*)malloc(sizeof(SSL));
printf("%p\n", iter->next);
iter = iter->next;
iter->next = (SSL*)0;
}

iter = FindPreItem(head, iter, 4);

printf("\n\n%p\n", iter );

return 0;
}

64,266

社区成员

发帖
与我相关
我的任务
社区描述
C++ 语言相关问题讨论,技术干货分享,前沿动态等
c++ 技术论坛(原bbs)
社区管理员
  • C++ 语言社区
  • encoderlee
  • paschen
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
  1. 请不要发布与C++技术无关的贴子
  2. 请不要发布与技术无关的招聘、广告的帖子
  3. 请尽可能的描述清楚你的问题,如果涉及到代码请尽可能的格式化一下

试试用AI创作助手写篇文章吧