给你单链表的头节点 head
,请你反转链表,并返回反转后的链表。
方法一:反转链表首先想到用一个栈存储链表里的val,利用栈FILO的特性,再遍历一次链表即可完成反转,O(N)的复杂度
class Solution {
public:
ListNode* reverseList(ListNode* head) {
if(head == NULL){
return head;
}
ListNode* pre = head;
stack<int> stack1;
while(pre != NULL){
stack1.push(pre->val);
pre = pre->next;
}
pre = head;
while(pre != NULL){
pre->val = stack1.top();
stack1.pop();
pre = pre->next;
}
return head;
}
};
方法二:官方答案要简洁许多,还得狠狠的学
class Solution {
public:
ListNode* reverseList(ListNode* head) {
ListNode* pre = NULL;
ListNode* cur = head;
while(cur){
ListNode* next = cur->next;
cur->next = pre;
pre = cur;
cur = next;
}
return pre;
}
};