【100题】反转链表(递归实现)
来源:互联网 发布:led旋转显示彩色,源码 编辑:程序博客网 时间:2024/04/28 19:15
//#include <iostream>using namespace std;struct ListNode{int data;struct ListNode *next;};//创建链表void createList(ListNode *&Head){ int num = 0; int flag = 0; ListNode *p = NULL; cin >> num; Head = (ListNode *)malloc(sizeof(ListNode)); while(num != 0) { if(flag == 0) { Head->data = num; Head->next = NULL; flag = 1; p = Head; } else { ListNode *cur = (ListNode *)malloc(sizeof(ListNode)); cur->data = num; cur->next = NULL; p->next = cur; p = cur; } cin >> num; }}//打印链表void printList(ListNode *Head){ if(Head == NULL) { cout << "Head empty"<<endl; return ; } ListNode *p = Head; while(p != NULL) { cout << p->data <<" "; p = p->next; }}//递归反转链表ListNode* reverseLinkList_recursion(ListNode* pNode,ListNode*& head){ if(pNode == NULL || pNode->next == NULL) { head->next = NULL; //把反转后的最后一个节点的next域置为NULL head = pNode; return pNode; } ListNode* tmpNode = reverseLinkList_recursion(pNode->next,head);//返回原链表中pNode的下一个节点 tmpNode->next = pNode; return pNode;}void main(){ ListNode *List = NULL; cout << "创建链表:"; createList(List); cout << "链表元素:"; printList(List); reverseLinkList_recursion(List,List); cout <<endl<< "倒序后:"; printList(List);}