#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;
}
1、从尾到头打印链表
最新推荐文章于 2024-02-14 20:22:16 发布