逆向打印与销毁单链表

来源:互联网 发布:怎么用网络连接打印机 编辑:程序博客网 时间:2024/05/06 17:47

逆向打印单链表:

#include <iostream>using namespace std;struct Node{    Node(int data)        :_data(data)        ,_next(NULL)    {}    Node* _next;    int _data;};void PrintListFromTailToHead(Node* pHead){    if(pHead == NULL)    {        return;    }    else    {        PrintListFromTailToHead(pHead->_next);        cout<<pHead->_data<<"->";    }}//void PrintListFromTailToHead(Node* pHead)//{//  if(pHead != NULL)//  {//      PrintListFromTailToHead(pHead->_next);//      cout<<pHead->_data<<"->";//}void FunTest(){    Node n1(1);    Node n2(2);    Node n3(3);    Node n4(4);    Node n5(5);    n1._next = &n2;    n2._next = &n3;    n3._next = &n4;    n4._next = &n5;    n5._next = NULL;}int main(){    FunTest();    return 0;}

逆向销毁单链表:

#include <iostream>using namespace std;struct Node{    Node(int data)        :_data(data)        ,_next(NULL)    {}    Node* _next;    int _data;};void DestroyListFromTailToHead(Node** pHead){    if(pHead)    {        DestroyListFromTailToHead(&((*pHead)->_next));        delete *pHead;        pHead = NULL;    }}void FunTest(){    Node* p1 = new Node(1);    Node* p2 = new Node(2);    Node* p3 = new Node(3);    Node* p4 = new Node(4);    Node* p5 = new Node(5);    p1->_next = p2;    p2->_next = p3;    p3->_next = p4;    p4->_next = p5;    p5->_next = NULL;    DestroyListFromTailToHead(&p1);}int main(){    FunTest();    system("pause");    return 0;}
0 0