算法刷题:LC初级算法(四)
2021/5/6 22:25:27
本文主要是介绍算法刷题:LC初级算法(四),对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!
文章目录
- 删除链表中的节点
- 删除链表的倒数第N个节点
- 反转链表
- 回文链表
删除链表中的节点
请编写一个函数,使其可以删除某个链表中给定的(非末尾)节点。传入函数的唯一参数为 要被删除的节点 。
示例 1:
输入:head = [4,5,1,9], node = 5 输出:[4,1,9] 解释:给定你链表中值为 5 的第二个节点,那么在调用了你的函数之后,该链表应变为 4 -> 1 -> 9.
示例 2:
输入:head = [4,5,1,9], node = 1 输出:[4,5,9] 解释:给定你链表中值为 1 的第三个节点,那么在调用了你的函数之后,该链表应变为 4 -> 5 -> 9.
提示:
链表至少包含两个节点。 链表中所有节点的值都是唯一的。 给定的节点为非末尾节点并且一定是链表中的一个有效节点。 不要从你的函数中返回任何结果。
作者:力扣 (LeetCode)
链接:https://leetcode-cn.com/leetbook/read/top-interview-questions-easy/xnarn7/
来源:力扣(LeetCode) 著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。
其实一开始我也没看太懂这个函数签名是什么意思,然后慢慢就懂了。
void deleteNode(ListNode* node) { node->val = node->next->val; node->next = node->next->next; }
删除链表的倒数第N个节点
给你一个链表,删除链表的倒数第 n 个结点,并且返回链表的头结点。
进阶:你能尝试使用一趟扫描实现吗?
思路:快慢指针。
先用快指针前进n,再用两个指针同时前进,这时候快指针到尾就是慢指针倒数第n的距离了。
ListNode* removeNthFromEnd(ListNode* head, int n) { ListNode * fast = head; ListNode * slow = head; for(;n>0;n--) fast = fast->next; if(fast == NULL) return head->next; while(fast->next != NULL && slow->next->next != NULL){ slow = slow->next; fast = fast->next; } slow->next = slow->next->next; return head; }
反转链表
思路:尾插法,这个真的又给我搞晕了。。。
ListNode* reverseList(ListNode* head) { ListNode* prev = nullptr; ListNode* curr = head; while (curr) { ListNode* next = curr->next; curr->next = prev; prev = curr; curr = next; } return prev; }
回文链表
请判断一个链表是否为回文链表。
从中间解开,后面半部分翻转。
然后开始一一匹配呗。
bool func(ListNode* node, int n, int depth) { if (n % 2 && depth == n / 2) { return true; } if (n % 2 == 0 && depth == n / 2 - 1) { int temp = node -> next -> val; node -> next = node -> next -> next; return temp == node -> val; } int future = func(node->next, n, depth + 1); node -> next = node -> next -> next; int ret = node -> val == node -> next -> val; node -> next = node -> next -> next; return ret && future; } bool isPalindrome(ListNode* head) { int n = 0; auto p = head; while (p) { n ++; p = p -> next; } if (n == 0 || n == 1) return true; return func(head, n, 0); }
这篇关于算法刷题:LC初级算法(四)的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!
- 2024-06-26小白家庭 nas 搭建方案-icode9专业技术文章分享
- 2024-06-23AI大模型企业应用实战(14)-langchain的Embedding
- 2024-06-23AI大模型企业应用实战(15)-langchain核心组件
- 2024-06-23AI大模型企业应用实战(16)-langchain核心组件
- 2024-06-23AI 大模型企业应用实战(06)-初识LangChain
- 2024-06-19EntBot.ai: AI Website Chatbot for Product Guides and Development Doc
- 2024-06-17zero-shot-learning-definition-examples-comparison
- 2024-06-06Package Easy(基于 NSIS 的打包exe安装包工具)使用方法-icode9专业技术文章分享
- 2024-06-06基于 casdoor 的 ELK 开源登录认证解决方案: elk-auth-casdoor-icode9专业技术文章分享
- 2024-05-29Elasticsearch慢查询日志配置