从尾到头打印链表

#include <stack>

#include <stdio.h>

typedef struct ListNode

{

 int m_nValue;

 ListNode *m_pNext;

}ListNode;

ListNode *createListNode(int value)

{

 ListNode *node = new ListNode();

 node->m_nValue = value;

 node->m_pNext = NULL;

 return node;

}

void connectListNode(ListNode *currentNode, ListNode *nextNode)

{

   if(currentNode == NULL)  

  {   

   printf("error");

   return;  

  }

 currentNode->m_pNext = nextNode;

}

void destroyList(ListNode *head) {  

  ListNode *node = head;

     if(node)

      {   

        head = head->m_pNext;

        delete node;

        node = head;

     }

}

void printList(ListNode *head) {

     printf("原先列表:\n");

     ListNode *node = head;

     while(node)

    {

       printf("%d ", node->m_nValue);

        node = node->m_pNext;

     }

    printf("\n");

  }

void printListReversingly(ListNode *head)

   {

      std::stack<ListNode *> nodes;

      ListNode *node = head;

     while(node != NULL)

    {   

       nodes.push(node);  

       node = node->m_pNext;

     }

 while(!nodes.empty())  

  {   

       node = nodes.top();

       printf("%d ", node->m_nValue);

      nodes.pop();

   }

}

void main()

{  

ListNode *node1 = createListNode(1);

 ListNode *node2 = createListNode(2);  

ListNode *node3 = createListNode(3);

 ListNode *node4 = createListNode(4);

 ListNode *node5 = createListNode(5);

 connectListNode(node1, node2);

 connectListNode(node2, node3);

 connectListNode(node3, node4);

 connectListNode(node4, node5);

 printList(node1);

 printf("从尾到头打印列表:\n");

 printListReversingly(node1);

 printf("\n");

 destroyList(node1);

}

posted @ 2013-08-27 11:50  lysxc  阅读(201)  评论(0编辑  收藏  举报