首页 > 代码库 > 如何实现单链表反转
如何实现单链表反转
#include <iostream> #include <algorithm> #include "string.h" #include "stdio.h" #include <vector> #include <deque> #include<stack> using namespace std; struct ListNode { int val; struct ListNode *next; ListNode(int x) : val(x), next(NULL) {} }; class Reverse { public: //非递归实现
ListNode* chkIntersect(ListNode* headA) { ListNode* head = NULL; ListNode* pNode = headA; ListNode* preNode = NULL; while(pNode !=NULL) { ListNode* pNext = pNode->next; if(pNext == NULL) head = pNode; pNode->next = preNode; preNode = pNode; pNode = pNext; } return head; } //递归实现 ListNode* chkIntersect1(ListNode* headA) { ListNode* pNode = headA; ListNode* node = chk(pNode,headA); cout<<headA->val<<endl; cout<<node->val<<endl; node->next = NULL; return headA; } ListNode* chk(ListNode* pNode,ListNode* &headA) { if(pNode == NULL || pNode->next == NULL) { headA = pNode; return pNode; } else { ListNode* node = chk(pNode->next,headA); node->next = pNode; node = node->next; return node; } } }; int main() { vector<int> res; res.push_back(1); res.push_back(2); res.push_back(3); res.push_back(4); res.push_back(5); vector<int> nxt; nxt.push_back(1); nxt.push_back(2); nxt.push_back(3); nxt.push_back(4); nxt.push_back(0); ListNode* pRoot = new ListNode(res[0]); ListNode* preNode = pRoot; int i=0; while(nxt[i]!=0) { ListNode* curNode = new ListNode(res[nxt[i]]); i++; preNode->next = curNode; preNode = curNode; } Reverse solution; ListNode* node=solution.chkIntersect1(pRoot); while(node) { cout<<node->val<<" "; node=node->next; } return 0; }
如何实现单链表反转
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。