牛客题解 | 【模板】链表

news/2025/2/21 17:42:01/文章来源:https://www.cnblogs.com/wc529065/p/18729691

题目

题目链接

解题思路

  1. 插入操作

    • 创建一个新节点。
    • 如果链表为空,直接将新节点作为头节点。
    • 遍历链表,找到第一个值为 x 的节点,在其前插入新节点。
    • 如果没有找到 x,将新节点插入到链表末尾。
  2. 删除操作

    • 如果链表为空,直接返回。
    • 如果头节点的值为 x,直接删除头节点。
    • 遍历链表,找到第一个值为 x 的节点,删除该节点。
  3. 输出链表

    • 遍历链表输出每个节点的值。
    • 如果链表为空,输出 "NULL"。

代码

#include <iostream>
#include <string>
using namespace std;struct ListNode {int val;ListNode* next;ListNode(int x) : val(x), next(nullptr) {}
};class LinkedList {
private:ListNode* head;public:LinkedList() : head(nullptr) {}void insert(int x, int y) {ListNode* newNode = new ListNode(y);if (!head) {head = newNode;return;}if (head->val == x) {newNode->next = head;head = newNode;return;}ListNode* prev = nullptr;ListNode* curr = head;while (curr && curr->val != x) {prev = curr;curr = curr->next;}if (prev) {newNode->next = prev->next;prev->next = newNode;} else {newNode->next = head;head = newNode;}}void deleteNode(int x) {if (!head) return;if (head->val == x) {ListNode* temp = head;head = head->next;delete temp;return;}ListNode* prev = nullptr;ListNode* curr = head;while (curr && curr->val != x) {prev = curr;curr = curr->next;}if (curr) {prev->next = curr->next;delete curr;}}void printList() {if (!head) {cout << "NULL" << endl;return;}ListNode* curr = head;while (curr) {cout << curr->val << " ";curr = curr->next;}cout << endl;}
};int main() {int n;cin >> n;LinkedList list;string op;while (n--) {cin >> op;if (op == "insert") {int x, y;cin >> x >> y;list.insert(x, y);} else if (op == "delete") {int x;cin >> x;list.deleteNode(x);}}list.printList();return 0;
}
import java.util.Scanner;class ListNode {int val;ListNode next;ListNode(int x) { val = x; }
}class LinkedList {private ListNode head;public LinkedList() {head = null;}public void insert(int x, int y) {ListNode newNode = new ListNode(y);if (head == null) {head = newNode;return;}if (head.val == x) {newNode.next = head;head = newNode;return;}ListNode prev = null;ListNode curr = head;while (curr != null && curr.val != x) {prev = curr;curr = curr.next;}if (prev != null) {newNode.next = prev.next;prev.next = newNode;} else {newNode.next = head;head = newNode;}}public void deleteNode(int x) {if (head == null) return;if (head.val == x) {head = head.next;return;}ListNode prev = null;ListNode curr = head;while (curr != null && curr.val != x) {prev = curr;curr = curr.next;}if (curr != null) {prev.next = curr.next;}}public void printList() {if (head == null) {System.out.println("NULL");return;}ListNode curr = head;while (curr != null) {System.out.print(curr.val + " ");curr = curr.next;}System.out.println();}
}public class Main {public static void main(String[] args) {Scanner sc = new Scanner(System.in);int n = sc.nextInt();LinkedList list = new LinkedList();for (int i = 0; i < n; i++) {String op = sc.next();if (op.equals("insert")) {int x = sc.nextInt();int y = sc.nextInt();list.insert(x, y);} else if (op.equals("delete")) {int x = sc.nextInt();list.deleteNode(x);}}list.printList();}
}
class ListNode:def __init__(self, x):self.val = xself.next = Noneclass LinkedList:def __init__(self):self.head = Nonedef insert(self, x, y):new_node = ListNode(y)if not self.head:self.head = new_nodereturnif self.head.val == x:new_node.next = self.headself.head = new_nodereturnprev = Nonecurr = self.headwhile curr and curr.val != x:prev = currcurr = curr.nextif prev:new_node.next = prev.nextprev.next = new_nodeelse:new_node.next = self.headself.head = new_nodedef delete(self, x):if not self.head:returnif self.head.val == x:self.head = self.head.nextreturnprev = Nonecurr = self.headwhile curr and curr.val != x:prev = currcurr = curr.nextif curr:prev.next = curr.nextdef print_list(self):if not self.head:print("NULL")returncurr = self.headwhile curr:print(curr.val, end=" ")curr = curr.nextprint()# 读取输入
n = int(input())
linked_list = LinkedList()for _ in range(n):op = input().strip().split()if op[0] == "insert":x, y = int(op[1]), int(op[2])linked_list.insert(x, y)elif op[0] == "delete":x = int(op[1])linked_list.delete(x)linked_list.print_list()

算法及复杂度分析

算法:

  • 链表的基本操作

时间复杂度:

  • 插入操作(insert):\(\mathcal{O}(n)\)

    • 需要遍历链表找到插入位置
    • 最坏情况下需要遍历整个链表
  • 删除操作(delete):\(\mathcal{O}(n)\)

    • 需要遍历链表找到要删除的节点
    • 最坏情况下需要遍历整个链表
  • 打印操作(print_list):\(\mathcal{O}(n)\)

    • 需要遍历整个链表输出所有节点
  • 总体时间复杂度:\(\mathcal{O}(qn)\)

    • \(q\) 是操作次数
    • \(n\) 是链表长度
    • 每个操作最坏情况下都需要遍历整个链表

空间复杂度:

  • 链表存储:\(\mathcal{O}(n)\)

    • \(n\) 是链表的节点数
    • 每个节点需要存储值和指针
  • 其他变量:\(\mathcal{O}(1)\)

    • 只需要少量额外变量来处理操作
  • 总体空间复杂度:\(\mathcal{O}(n)\)

    • 主要由链表本身的存储空间决定

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.hqwc.cn/news/887685.html

如若内容造成侵权/违法违规/事实不符,请联系编程知识网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

BUUCTF-Web方向16-20wp

[极客大挑战 2019]PHP 由内容提示应该存在源码备份,常见的如下,一个个尝试 后缀:tar tar.gz zip rar 名字:www web website backup back wwwroot temp访问www.zip,下载下来解压查看index.phpflag.phpclass.php <?php include flag.php;error_reporting(0);class Name{…

【Nginx开发】如何使用Nginx搭建旁路服务器获取客户端IP

一、前言 在实际业务开发过程中,很多时候有记录客户端真实IP的需求,但是从客户端发送的请求往往会经过很多代理服务器,导致后端服务获取的IP为代理以后的IP,不具有业务含义。为了解决这个问题,可以搭建一个旁路服务器,前端在发起请求的时候需要先请求旁路服务器,获取该客…

PyBy2:若依计划任务自动化上线+内存马自动生成v2.0

免责声明 本公众号文章以技术分享学习为目的。由于传播、利用本公众号发布文章而造成的任何直接或者间接的后果及损失,均由使用者本人负责,公众号及作者不为此承担任何责任。一旦造成后果请自行承担!如有侵权烦请告知,我们会立即删除并致歉。谢谢!前言 攻防中,遇到一个ruo…

当任务失败时,顶级调度系统如何实现分钟级数据补偿?

一、补数机制的定义与挑战 补数(Backfill) 指在数据管道因系统故障、数据延迟或逻辑错误导致历史任务缺失时,重新调度并执行指定时间范围内的工作流以修复数据缺口。在大数据场景中,补数机制需解决三大核心挑战:复杂依赖链重建:需精准识别历史时间段内任务上下游关系,避…

绿色建筑设计原则与案例分析 - 如何将环保理念融入建筑设计中

在这个追求可持续发展的时代,绿色建筑不仅是一种趋势,更是对地球未来的责任和承诺。它旨在通过最少的环境影响,提供健康、高效、舒适的生活与工作空间。本文将深入探讨绿色建筑设计的核心原则,并通过具体案例分析,揭示如何将环保理念巧妙融入建筑设计之中,为读者呈现一场…

Windows 程序隐藏启动黑窗口总结

免责声明: 该公众号分享的安全工具和项目均来源于网络,仅供安全研究与学习之用,如用于其他用途,由使用者承担全部法律及连带责任,与工具作者和本公众号无关。以下文章来源于锦鲤安全 ,作者四五qq 前言 Windows 控制台程序在启动时会出现一个黑(dos)窗口,一般我们想要隐…

docker部署.net core3.1

1.安装dockerapt install docker.io2.拉取.net core依赖镜像docker pull mcr.microsoft.com/dotnet/core/aspnet:latest3.创建.net core3.1项目 选择docker支持,会生成dockerFile配置文件如图:4.编写dockerfile文件,经删减后为:FROM mcr.microsoft.com/dotnet/core/aspnet:3…

DeepSeek 满血版在 VScode 和 IDEA 中怎么用?手把手教程来了

DeepSeek 满血版在 IDEA 中怎么用?手把手教程来了作者:沉默王二近期有几个热点事件,不知道大家关注到没有?第一个标志事件,一向挑剔的苹果宣布和阿里合作,一起为国行版 iPhone 提供 AI 技术服务。 第二个标志事件,DeepSeek R1 蒸馏了 6 个模型开源给社区,其中有 4 个来…

redission-delay-queue使用及原理

1.引入jar包<dependency><groupId>xxxx.delay</groupId><artifactId>redisson-delayed-queue</artifactId><version>1.0.0-SNAPSHOT</version> </dependency>2.客户端代码开发2.1:新增实现BaseTask的bean 参数由业务自行决定…

利用网页爬虫从专业产品论坛提取评论的完整指南

了解如何通过网页爬虫从专业产品论坛提取评论,以获取可操作的洞见、改进策略,并节省时间。利用网页爬虫从专业产品论坛提取评论已经成为企业的游戏规则改变者。它使您能够从多个平台收集客户反馈(https://dataforest.ai/blog/top-web-scraping-use-cases),实时监控情绪,并自…

树的重心(树形dp)

我最开始将n减了1,应为边长有n-1条,但是这会导致计算时出现错误,因为其他地方会用到n#include<iostream> #include<vector> using namespace std; const int N=1e5+5; vector<int>v[N]; int f[N]; int vis[N]; int ans=1e5; int n; int dfs(int x){vis[x]…

仓库管理到底该怎么管?记住这五常六准原则!

仓库管理到底该怎么管? 要是你觉得仓库只是个“堆货的地方”,那可就大错特错了! 想象一下,货物乱成一团,找东西时费劲,出库慢,结果错发了货,那可真的是“大麻烦”啊。 客户打电话来投诉,老板又来催货,这种情况谁遇到谁头疼。 但其实,仓库管理不复杂,只要掌握了一些…