剑指offer 16---单链表的逆置

来源:互联网 发布:汉字笔顺软件下载 编辑:程序博客网 时间:2024/06/16 21:40

单链表的逆置

非递归实现

#include <iostream>#include <Windows.h>using namespace std;struct ListNode{int _value;ListNode* _next;ListNode(const int& value):_value(value), _next(NULL){}};//单链表的逆置    非递归实现ListNode* ReverseList(ListNode* pHead){if (pHead == NULL){return NULL;}if (pHead->_next == NULL){return pHead;}ListNode* cur = pHead;   //当前头结点ListNode* ReverseHead = NULL;   //逆置后的头结点ListNode* prev = NULL;while (cur){ListNode* next = cur->_next;if (next == NULL){ReverseHead = cur;}cur->_next = prev;   //逆转的过程,并且能将头结点的prev置为NULLprev = cur;cur = next;}return ReverseHead;}int main(){ListNode* pHead = new ListNode(1);ListNode* p = pHead;ListNode* q = pHead;for (int i = 2; i <= 10; ++i){ListNode* temp = new ListNode(i);p->_next = temp;p = temp;}cout << "原始链表: " << "";while (q){cout << q->_value << "->";q = q->_next;}cout << endl;ListNode* ppy = ReverseList(pHead);cout << "逆转后的链表: " << "";while (ppy != NULL){cout << ppy->_value << "->";ppy = ppy->_next;}cout << endl;system("pause");return 0;}




原创粉丝点击