003.单链表的反转
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode() : val(0), next(nullptr) {}
* ListNode(int x) : val(x), next(nullptr) {}
* ListNode(int x, ListNode *next) : val(x), next(next) {}
* };
*/
1.递归算法
要反转单链表,就要从最后一个节点开始向前连,需要知道节点和它前一个节点的指针,dfs可以实现这一功能
class Solution {
public:
ListNode* reverseList(ListNode* head) {
if(head == NULL || head -> next == NULL){
return head;
}
ListNode* newhead = reverseList(head->next);
head->next->next=head;
head->next=NULL;
return newhead;
}
};
时间复杂度:\(O(n)\)
2.非递归算法
使用迭代的方法也可以,需要多个指针来维护节点信息
pre->cur->temp反转后变成pre<-cur temp
class Solution {
public:
ListNode* reverseList(ListNode* head) {
ListNode* pre = NULL;
ListNode* cur = head;
while(cur){
ListNode* temp = cur -> next;
cur -> next = pre;
pre = cur;
cur = temp;
}
return pre;
}
};
时间复杂度:\(O(n)\)

浙公网安备 33010602011771号