剑指offer 16- 反转链表

来源:互联网 发布:mac无苹果安装win7系统 编辑:程序博客网 时间:2024/05/19 00:39


#include <iostream>#include <stack>using namespace std;//无头节点struct ListNode{int       m_nValue;ListNode* m_pNext;};void  InsertListNode( ListNode **head,  int value) { ListNode* p= new ListNode(); p->m_nValue = value; p->m_pNext = NULL; if (*head == NULL) { *head = p; } else {  ListNode* node = *head; while(node->m_pNext != NULL) node = node->m_pNext; node->m_pNext = p;  } }ListNode * ReverseListNode(ListNode *head){ListNode * p=NULL;ListNode *pNext=NULL;    while(head != NULL){pNext = head->m_pNext;head->m_pNext = p;p = head;head = pNext;}return p;}void printListNode(ListNode * node){while(node!=NULL){cout<<node->m_nValue <<" ";node = node->m_pNext;} cout<<endl;}int main(int argc, char* argv[]){ListNode *head = NULL;int a[]= {1,2,3,4,5};for(int i=0;i<sizeof(a)/sizeof(int);i++){  InsertListNode( &head,a[i]);}printListNode(head);head = ReverseListNode(head);printListNode(head);head = ReverseListNode(NULL);  //空指针printListNode(head); return 0;}


0 0
原创粉丝点击