数据结构 倒序打印链表结点

tests.h

#include<iostream>

using namespace std;

struct ListNode{

ListNode(){};

int data;   

ListNode *next;

};

class tests
{
public:


void ShowListReverse(ListNode* head);
private:
ListNode * head;


};

void tests::ShowListReverse(ListNode *head) {
if(head!=NULL)
{
if(head->next!=NULL)
{ShowListReverse(head->next);
cout<<head->data<<endl;
}
else{
cout<<head->data<<endl;
}
}

}

main.cpp
#include"tests.h"
#include<iostream>
using namespace std;
int main() {
tests tests;
ListNode *phead = new ListNode();
ListNode *normal,*ptemp;
ptemp=phead;
int a[5] = {1, 4, 2, 5, 6};
for (int i = 0; i < 5; i++)
{
normal = new ListNode;
normal->data = a[i];
normal->next = NULL;
ptemp->next = normal;
ptemp = normal;
}
//以上程序段是利用数组生成一个链表,生成的链表pHead为{0, 1, 4, 2, 5, 6},可以看出多了初始头结点0
ListNode * head=phead->next;//去掉初始头结点
cout << "利用递归方法从尾到头反过来打印链表的值如下:" << endl;
tests.ShowListReverse(head);
cout << endl;
return 0;
}

猜你喜欢

转载自www.cnblogs.com/wwqdata/p/11619361.html