您的位置:首页 > 编程语言 > C语言/C++

单链表逆序输出C++ (stack方法、双向链表方法以及vector方法)

2017-03-01 17:52 399 查看
#include "stdio.h"
#include <iostream>
#include "malloc.h"
#include <stack>
#include <vector>

struct listNode{
listNode*  next;
int nodeData;
};
struct twoDlistNode
{
twoDlistNode *next;
twoDlistNode * pre;
int nodeData;
};

int listData[] = {5,52,4,6,2,445,6,1,52,465,1};

void buildList(listNode* head)
{
int i=1;
listNode* tmp,*tmpold;
int count = sizeof(listData)/4;
head->nodeData = listData[0];
tmpold = head;
for(;i<count;i++)
{
tmp = new listNode();
tmp->nodeData = listData[i];
tmpold->next = tmp;
tmpold = tmp;
}
tmp -> next = NULL;
}

void twoD_method(listNode *tmp)
{
twoDlistNode *twoD,*twoDtmp,*twoDtmpold;
if(!tmp)
return ;
twoD = new twoDlistNode();
twoD->pre = NULL;
twoD->nodeData = tmp->nodeData;
twoD->next = NULL;
tmp = tmp->next;
twoDtmpold = twoD;
while(tmp)
{
twoDtmp = new twoDlistNode();
twoDtmp->nodeData = tmp->nodeData;
twoDtmp-> pre = twoDtmpold;
twoDtmpold->next = twoDtmp;
twoDtmpold = twoDtmp;
tmp = tmp->next;
}
printf("This is the twoD_method:\n");
while(twoDtmpold)
{
printf("%d\n",twoDtmpold->nodeData );
twoDtmpold = twoDtmpold->pre;
}
}

void stack_method(listNode *tmp)
{
listNode *getNode;
int getdata;
std::stack<listNode*> mystack;
while(tmp->next)
{
mystack.push(tmp);
tmp = tmp->next;
}
mystack.push(tmp);
printf("This is the stack_method:\n");
while(!mystack.empty())
{
getNode = mystack.top();
getdata = getNode->nodeData;
printf("%d\n",getdata);
mystack.pop();
}
}

void vectorMethod(listNode *tmp)
{
std::vector<int> myvector;
if (tmp==NULL)
return;
listNode* vMtmp = tmp;
while(vMtmp)
{
myvector.push_back(vMtmp->nodeData);
vMtmp = vMtmp->next;
}
printf("This is the vectorMethod\n");
for(std::vector<int>::iterator iter = myvector.end()-1;iter != myvector.begin()-1;iter--)
printf("%d\n",*iter );
}

int main(void)
{
listNode* list;
list = new listNode();
listNode* tmp;
tmp = list;
buildList(list);
twoD_method(tmp);
stack_method(tmp);
vectorMethod(tmp);
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  c语言 链表
相关文章推荐