【100题】反转链表(递归实现)
2012-07-25 22:52
337 查看
// #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); }
相关文章推荐
- python中使用递归实现反转链表
- 单链表反转(非递归java实现)
- 反转链表的迭代实现和递归实现
- 反转链表:迭代和递归的实现
- 链表反转C实现(递归与循环)
- java-实现链表反转-递归和非递归实现
- 链表反转的递归和非递归实现方式
- 【leetcode】通过递归反转单链表 - Go语言实现
- java非递归实现单链表反转
- 递归和非递归实现链表反转
- 递归和非递归实现链表反转
- 链表的反转(递归实现和非递归实现)
- 链表反转的实现(递归反转链表,非递归反转链表)
- 实现链表的反转(递归方法与非递归方法)
- 递归实现链表反转
- 使用单链表反转的递归和非递归实现方式
- 链表反转(递归与非递归实现)
- 带头节点链表的反转 循环和递归 C#实现
- 一些常用算法[数组全排列算法,单链表反转(递归实现),字符串反转,桶排序]
- 遍历和递归实现双向链表反转