1、从尾到头打印链表

#include<iostream>
#include<string> 
#include<vector>
#include<stack>
#include<stdlib.h>

#include"algorithm"
using namespace std;

//链表结点
typedef struct _ListNode{
	int data;
	struct _ListNode* next;
}ListNode;

ListNode* LinkList_Create(int *value, int num)
{
	ListNode *pHead = (ListNode*)malloc(sizeof(ListNode));
	ListNode *pTail = pHead;
	
	for(int i = 0; i < num; i++)
	{
		ListNode *pCur	= (ListNode*)malloc(sizeof(ListNode));
		pCur->data 	= value[i];
		pTail->next = pCur;
		pTail		= pCur;
	}
	pTail->next = NULL;
	return pHead;
	 
} 

void PrintNode(ListNode *head)
{
	ListNode *p = head->next;
	for(;p;p = p->next)
	{
		printf("%d ",p->data);
	}	
	printf("\n");
}

//算法1: 
//for_each回调函数 
void show(int &n)
{
	cout << n << " ";
}
int  printListFormTailTohead1(ListNode *pHead)
{
	stack<int> nodes;
	vector<int> result;
	
	ListNode *pNode = pHead->next;
	while(pNode != NULL)
	{
		nodes.push(pNode->data);
		pNode = pNode->next;
	}	
	while(!nodes.empty())
	{
		result.push_back(nodes.top());
		nodes.pop();
	}
//	for(vector<int>::iterator it = result.begin(); it != result.end(); it++)
//	{
//		cout << *it << endl;
//	}

	for_each(result.begin(), result.end(), show);
	return 1;
} 
//算法2:
void  printListFormTailTohead2(ListNode *pHead)
{
	if(pHead == NULL)
		return ;
	ListNode *end = NULL;

	while(pHead->next != end)
	{
		ListNode *cur = pHead;
		while(cur->next != end)
		{
			cur = cur->next;
		}
		printf("%d ", cur->data);
		end = cur;
	}
}

//算法3  递归的方法  适用于不带头节点的链表 
 void printListFormTailTohead3(ListNode *pHead)
 {
 	if(pHead != NULL)
	 {
	 	printListFormTailTohead3(pHead->next);
	 	printf("%d ",pHead->data);
	 } 
 } 
  
int main()
{
	int data[7] = {2,3,6,4,5,7,9};
 	ListNode* pHead = LinkList_Create(data,7);
 	PrintNode(pHead);
 	
 	printListFormTailTohead1(pHead);
 	cout << endl;
	printListFormTailTohead2(pHead);
	cout << endl;
	//printListFormTailTohead3(pHead);
	return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值