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

#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);
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值