销售型网站设计,如何在抖音上投放广告,产品朋友圈推广词,怎么敲代码做网站链表解题技巧
额外的数据结构#xff08;哈希表#xff09;#xff1b;快慢指针#xff1b;虚拟头节点#xff1b;
反转链表
分别实现单向链表和双向链表的反转。
要求#xff1a;长度为N的链表#xff0c;时间复杂度为O(N)#xff0c;额外空间复杂度为O(1)。
反转…链表解题技巧
额外的数据结构哈希表快慢指针虚拟头节点
反转链表
分别实现单向链表和双向链表的反转。
要求长度为N的链表时间复杂度为O(N)额外空间复杂度为O(1)。
反转单向链表
方法1使用栈时O(N)空O(N)
第一次遍历将数据添加至栈中定义一个空节点tmp记录cur指向该节点栈不为空开始循环出栈 cur的next指向的栈顶元素栈顶元素出栈cur移动到next的位置 cur现在在最后一个位置将其next赋值为nullptrcur指向tmp空节点的next位置并删除tmp返回cur新的头节点
LinkedNode* LinkedList::reverseWithStack(LinkedNode *head) {if (head nullptr || head-next nullptr) {return head;}std::stackLinkedNode* stk;LinkedNode* cur head;while (cur) {stk.push(cur);cur cur-next;}LinkedNode* tmp new LinkedNode();cur tmp;while (!stk.empty()) {cur-next stk.top();stk.pop();cur cur-next;}cur-next nullptr;cur tmp-next;delete tmp;return cur;
}方法2双指针时O(N)空O(1)
双指针解法
定义两个指针new_headcur初始new_head指向headcur指向head的nextcur不为nullptr则开始循环 head的next赋值为cur的nextcur的next赋值为new_headnew_head移动到curcur移动到head的next 最后返回new_head即可。
LinkedNode* LinkedList::reverse(LinkedNode *head) {if (head nullptr || head-next nullptr) {return head;}LinkedNode *new_head head;LinkedNode *cur head-next;while (cur) {head-next cur-next;cur-next new_head;new_head cur;cur head-next;}return new_head;
}反转双链表
DoubleLinkedNode* LinkedList::reverseDoubleLinkedList(DoubleLinkedNode *head) {if (head nullptr || head-next nullptr) {return head;}DoubleLinkedNode *pre head;DoubleLinkedNode *cur head-next;while (cur) {DoubleLinkedNode *tmp pre-next;pre-next pre-pre;pre-pre tmp;pre cur;cur cur-next;}return pre;
}