解题思路:
- 方案一:采用暴力遍历的方式共计遍历两次,第一次遍历存储每一个结点的值,第二次反向遍历链接每一个结点的值,时间复杂度O(n),空间复杂度O(n)。
- 方案二:采用局部三指针交换指向进行反向链表,时间复杂度O(n),空间复杂度O(1)。
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
//方案一暴力遍历
class Solution {
public:
ListNode* reverseList(ListNode* head) {
vector<int> vec;
//遍历整个链表存储每一个结点的值
while(head!=NULL){
vec.push_back(head->val);
head = head->next;
}
//创建新链表头节点
ListNode* res = new ListNode(-1);
ListNode* temp = res;
//反向链接每一个结点的值
for(int i = vec.size()-1;i>=0;--i){
temp->next = new ListNode (vec[i]);
temp = temp->next;
}
return res->next;
}
};
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
//方案二:三指针局部交换链接
class Solution {
public:
ListNode* reverseList(ListNode* head) {
ListNode* pre = NULL;
ListNode* current = head;
ListNode* next = NULL;
while(current!=NULL){
next = current->next;
current->next = pre;
pre = current;
current = next;
}
return pre;
}
};
可参考动画演示:
https://leetcode-cn.com/problems/fan-zhuan-lian-biao-lcof/solution/shi-pin-tu-jie-jian-zhi-offer-24-fan-zhu-oym7/