在VS和Linux下逆序打印单链表(递归和非递归)

来源:互联网 发布:淘宝联盟怎么合并购买 编辑:程序博客网 时间:2024/06/08 15:32

vs

关于思路:

在打印单链表的时候,这个链表首先是得有东西的,所以首先得用头插或者尾插,在插入节点的时候,我们传入的值,光给值的话,无法真正把结点插进去,所以还应该有创建节点的操作,另外,逆序打印,我们有两种办法,一种是递归的办法,另一种是非递归的办法(用栈来实现,先 让结点入栈,在出栈,出栈顺序正好就是逆序的,用这个办法可以降低时间复杂度)

关于代码:

头文件:

#include<stdio.h>
#include<stdlib.h>
#include<stack>
#include<iostream>
using namespace std;
typedef struct Node
{
Node* next;
int _data;
}pNode;
pNode* pHead;
int data = 0;
pNode*  pushfront(pNode *pHead,int data);
void printListReverse(pNode *pHead);
void PrintListReverse(pNode *pHead);
void Print(pNode *pHead);


源文件:

#include"ttl.h"
pNode* createNode(int data)
{
pHead = (pNode*)malloc(sizeof(Node));
if (NULL == pHead)
return NULL;
else
{
pHead->next = NULL;
pHead->_data = data;
return pHead;
}
}
pNode*  pushfront(pNode *pHead,int data) //头插
{
pNode* insert = createNode(data);
if (pHead == NULL)
{
pHead->_data = data;
pHead->next = NULL;
pHead = insert;
}
else
{
insert->next = pHead;
insert->_data = data;
pHead = insert;
}
return pHead;
}
void Print(pNode*pHead) //顺序打印
{
while (pHead)
{
printf("%d->", pHead->_data);
pHead = pHead->next;
}
printf("\n");
}
void printListReverse(pNode *pHead)  //递归实现逆序打印
{
if (pHead == NULL)
return;
if(pHead->next!=NULL)
{
printListReverse(pHead->next);
}
printf("%d->", pHead->_data);
}
void PrintListReverse(pNode* pHead)  //非递归的逆序打印
{
if (pHead == NULL)
return;
stack<Node*>Node;
while (pHead)
{
Node.push(pHead);      
pHead = pHead->next;
}
while (!Node.empty())
{
pHead = Node.top();
printf("%d->",pHead->_data);
Node.pop();
}


}
int main()
{
pNode* pHead = createNode(1);
pHead = pushfront(pHead, 2);
pHead = pushfront(pHead, 3);
pHead = pushfront(pHead, 4);
Print(pHead);
printListReverse(pHead);
printf("\n");
PrintListReverse(pHead);
system("pause");
return 0;
}


运行结果:

 

Linux

在linux下编写,和vs的代码是一样的,但是要注意在写Makefile的时候由于很多头文件是C++中的,所以就不能再用gcc而要用g++如果用了gcc就会出现找不到文件各种报错。

Makefile


运行结果


原创粉丝点击