从尾到头输出链表、字符串;不声明变量计算字符串长度

1、可以用栈来做。每经过一个结点时,放入栈中。当遍历完链表后,在遍历栈即可。但是要维护一个栈,比较麻烦。

2、递归来实现。每访问一个结点,先递归输出它后面的结点,再输出该结点。这样就能实现从尾到头输出链表。


方法2的代码:

//58.从尾到头输出链表。
#include<iostream>
using namespace std;

struct node
{
	int data;
	node *next;
};

void Create(node *&head)
{
	int i;
	cin>>i;
	node *p1=NULL,*p2=NULL;
	while(i!=-1)
	{
		if(head==NULL)
		{
			head=new node;
			head->data=i;
			p1=head;
			p1->next=NULL;
		}
		else
		{
			p2=new node;
			p2->data=i;
			p1->next=p2;
			p1=p2;
			p1->next=NULL;
		}
		cin>>i;
	}
}

void Print( node *&head)
{
	if(head==NULL)
		return;
	else
	{
		Print(head->next);
		cout<<head->data<<endl;
	}
}
void main()
{
	node *head=NULL;
	Create(head);
	Print(head);
	system("pause");
}

扩展:该题还有两个常见的变体:

1. 从尾到头输出一个字符串;

2. 定义一个函数求字符串的长度,要求该函数体内不能声明任何变量。


1、

<span style="font-size:18px;">void P_str(char *p)
{
	
	if(*p=='\0')
		return;
	else
	{
		P_str(++p);
		cout<<*(p-1)<<endl;
	}

	
}</span>

2、

<span style="font-size:18px;">//定义一个函数求字符串的长度,要求该函数体内不能声明任何变量。

#include <iostream>
using namespace std;

int len(char *p)
{
	if(*p=='\0')
		return 0;
	else
		return 1+len(++p);
	
}
void main()
{
	char p[100];
	cin>>p;
	cout<<len(p)<<endl;
	system("pause");
}</span>


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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值