/* 题目: 定义一个函数,输入链表的头结点,反转链表输出反转后链表的头节点。 */ /* 思路: 记录当前节点的next和pre。 断开当前节点指向next的指针,指向pre。 */ #include <iostream> #include<cstdlib> using namespace std; struct ListNode { int val; struct ListNode *next; ListNode(int x) : val(x), next(NULL) { } }; ListNode* ReverseList(ListNode* pHead) { if(pHead == nullptr || pHead->next == nullptr) return pHead; ListNode* pre = pHead; ListNode* curr = pHead->next; pre->next = nullptr; ListNode* next = nullptr; while(curr){ next = curr->next; curr->next =pre; pre = curr; curr = next; } return pre; } int main() { ListNode *node6 = new ListNode(6); ListNode *node5 = new ListNode(5); ListNode *node4 = new ListNode(4); ListNode *node3 = new ListNode(3); ListNode *node2 = new ListNode(2); ListNode *node1 = new ListNode(1); ListNode *pHead = new ListNode(0); pHead->next = node1; node1->next = node2; node2->next = node3; node3->next = node4; node4->next = node5; node5->next = node6; node6->next = nullptr; pHead = ReverseList(pHead); cout<<"answer"<<endl; while(pHead != nullptr){ cout<<pHead->val<<endl; pHead = pHead->next; } cout << "Hello world!" << endl; return 0; }
原文:https://www.cnblogs.com/buaaZhhx/p/11904751.html