linked-list 相关问题

链表是一种数据结构,其中元素包含对下一个(以及可选的前一个)元素的引用。链接列表提供O(1)插入和删除具有已知内存位置的任何元素,O(1)列表并置,以及前(和可选后)位置的O(1)访问以及O(1)下一个元素访问。随机访问和随机索引插入/移除具有O(n)复杂性并且通常是未实现的。

C 程序遍历单链表

我编写了一个C程序来实现遍历单链表的概念。该程序首先通过请求用户输入来创建列表,然后显示/遍历创建的

回答 1 投票 0

我对python中的链表和节点感到困惑。我目前正在leetcode上做一道关于在k组中反转链表的问题

类解决方案: defverseKGroup(self, head: 可选[ListNode], k: int) -> 可选[ListNode]: 虚拟 = ListNode() prev_group = 虚拟 而头: j、组...

回答 1 投票 0

向整数数字的链表表示加一

我正在尝试解决这个挑战: 给定一个表示为非空单向数字链接列表的非负整数,为该整数加一。 您可以假设该整数不包含任何 l...

回答 1 投票 0

链表 addLast() 方法未按预期工作

根据 addLast() 的定义,addLast() 方法用于将元素添加到列表的最后一个。但在下面的代码中,这种情况没有发生。 LinkedList 演示 = 新 Linke...

回答 5 投票 0

使用reverseList解决链表循环问题

我最近尝试解决 LeetCode 问题 141,“链表循环”,问题的#link,我找到了一个可行的解决方案,但让我感到困惑。我希望得到一些澄清...

回答 1 投票 0

疑似指针算术错误导致意外输出

我正在尝试从头开始用 C++ 构建一个链表。考虑以下带注释的类声明。 /* 链表从小到大 */ 班级名单 { 民众: 列表():头(...

回答 1 投票 0

在 C 中修改链表头节点而不进行指针取消引用[重复]

void myLinkedListAddAtHead(MyLinkedList* obj, int val) { // 函数体 } 当我尝试将新节点链接到链表的头部时,问题就出现了。虽然我正在更新 obj poi...

回答 1 投票 0

posX 无法解析或不是字段

我在处理时使用了一个自行实现的链接列表,并且刚刚发生了错误: posX 无法解析或不是字段 这是我的代码: 主要类别: 列表 GarbageList = new ...

回答 1 投票 0

递归反转链表时出现问题

为什么这段反转链表的代码不起作用?我想确切地知道我做错了什么。 struct ListNode* reverseList(struct ListNode* head) { if(head==NULL || head->next==NULL) ...

回答 1 投票 0

Object Pascal 链表析构函数留下一个块未释放

在Object Pascal中实现这个单链表类的析构函数,为什么最后总是有一个内存块未释放? 我尝试过迭代而不是递归破坏......

回答 1 投票 0

循环链表定义

我正在尝试在 Rust 中创建一个循环链表定义,并提出了以下实现: pub 结构 ListNode { 酒吧值:i32, 酒吧下一个:选项 我正在尝试在 Rust 中创建一个循环链表定义,并提出了以下实现: pub struct ListNode { pub val: i32, pub next: Option<Rc<RefCell<ListNode>>>, } impl ListNode { pub fn new(val: i32) -> Self { ListNode { next: None, val } } pub fn for_each<F>(&self, f: F) -> () where F: Fn(i32), { f(self.val); while let Some(next) = &self.next { f(next.borrow_mut().val); } } } 问题是运行以下代码时出现紧急错误:already borrowed: BorrowMutError fn main() { let lst = Rc::new(RefCell::new(ListNode::new(10))); let mut ref_mt = lst.borrow_mut(); ref_mt.next = Some(lst.clone()); lst.clone().borrow_mut().for_each(|val| println!("{}", val)) } 有没有办法修复代码,使其与 RefCell 一起工作,或者 RefCell 本质上不适合这种情况? 在(安全)Rust 程序中,数据最多可以有一个可变引用,该引用由“所有权规则”控制并由“借用检查器”强制执行。用 Rc 包装类型不会改变 here 所讨论的情况,这也是使用 RefCell 的原因。它使用“内部可变性”来允许表面上看起来像多个可变引用。然而,正如here所讨论的,相同的规则适用,它们只是“动态”检查(即在运行时,而不是在编译时)。这就是你在这里遇到的问题。曾经有一个时间点违反了“别名 XOR 可变性”规则。让我们看看哪里出了问题。 首先,当尝试调用 ref_mt(可变借用 2)时,for_each 仍在范围内(可变借用 1)。让我们通过显式删除 ref_mt 来解决这个问题。let mut ref_mt = lst.borrow_mut(); ref_mt.next = Some(lst.clone()); drop(ref_mt); lst.clone().borrow_mut().for_each(|val| println!("{}", val)) 进行此更改后,至少会打印一次“10”。接下来,在尝试迭代时该节点仍保持借用状态,迭代本身将尝试借用同一节点。让我们通过避免不必要的借用来解决这个问题。 lst.clone().borrow().for_each(|val| println!("{}", val)) 接下来,我们在无限迭代中遇到同样的问题。让我们以同样的方式解决这个问题。 f(next.borrow().val); 最后,循环开始工作,只要您允许,程序就会继续循环打印“10”。 修改后的代码完整版: use std::{cell::RefCell, rc::Rc}; pub struct ListNode { pub val: i32, pub next: Option<Rc<RefCell<ListNode>>>, } impl ListNode { pub fn new(val: i32) -> Self { ListNode { next: None, val } } pub fn for_each<F>(&self, f: F) -> () where F: Fn(i32), { f(self.val); while let Some(next) = &self.next { f(next.borrow().val); } } } fn main() { let lst = Rc::new(RefCell::new(ListNode::new(10))); let mut ref_mt = lst.borrow_mut(); ref_mt.next = Some(lst.clone()); drop(ref_mt); lst.clone().borrow().for_each(|val| println!("{}", val)) }

回答 1 投票 0

通过交换节点的链表选择排序

作业是通过交换节点而不是值来使用选择排序。当排序算法更改最后一个节点时,它会引发 AttributeError,因为看起来 def min_sort() 中的first.next...

回答 1 投票 0

我无法在简单链接列表中拆分偶数[已关闭]

我发现自己陷入了一个问题。我想创建一个采用列表的函数,例如: 1 2 3 4 5 6 将偶数除以 2 4 是 2 2 6 是 2 2 2 和...

回答 1 投票 0

将链表传递给函数 LeetCode Add2number

我在做leetcode问题时意识到我以前从未将链表传递给函数。所以,现在我正在尝试使用继承 li 结构的类来实现链表...

回答 1 投票 0

我无法在简单链接列表中复制偶数[已关闭]

我发现自己陷入了一个问题。如何在简单链表中将偶数复制为 2?我试图通过人工智能回答这个问题,但它没有给我我想要的输出......

回答 1 投票 0

有没有更简洁的方法来编写此 C++ 代码?

我正在学习 C++,来自动态类型语言背景,并在 C++ 中实现算法来完成此学习。我当前的(子)项目是一个将元素插入到...

回答 1 投票 0

XML 脚本运行以打印所需的输出

我有一个示例 XML 输入文件,其中包含以下内容: 我有一个示例 XML 输入文件,其中包含以下内容: <?xml version="1.0" encoding="utf-8"?> <infobases> <infobase author="Chartered Professional Accountants of Canada" levelDefOrder="Level 1,Level 2,Level 3,Level 4,Level 5,Level 6,Level 7,Level 8,Level 9,Level 10,Level 11,Level 12,Level 13,Normal Level" levels="Level 1,Level 2,Level 3,Level 4,Level 5,Level 6,Level 7,Level 8,Level 9,Level 10,Level 11,Level 12,Level 13" name="info_a" title="CPA Canada Standards and Guidance Collection"> <file level="Level 1" heading="XYZ1-L1">XYZ1-L1 <file level="Level 2" heading="XYZ1-L12">XYZ1-L12 <file level="Level 3" heading="XYZ1-L123">XYZ1-L123</file> <file level="Level 3" heading="XYZ1-L123">XYZ1-L123</file> <file level="Level 3" heading="XYZ1-L123">XYZ1-L123</file> </file> </file> <file level="Level 1" heading="XYZ2-L1">XYZ2-L1</file> <file level="Level 1" heading="XYZ2-L1">XYZ2-L1 <file level="Level 2" heading="XYZ2-L12">XYZ2-L12</file> <file level="Level 2" heading="XYZ2-L123">XYZ2-L123 <file level="Level 3" heading="XYZ1-L123">XYZ1-L123 <file level="Level 4" heading="XYZ1-L123">XYZ1-L123</file> </file> </file> </file> </infobase> </infobases> 我想编写一个脚本来识别文件元素级别属性,并在打印文件元素的标题时给出适当的缩进。文件元素标题将获得 .ditamap 扩展名,该扩展名将其他文件元素作为子元素并忽略其他子元素(不在示例 xml 文件中)。如果文件元素没有子文件元素,则会添加 .dita 扩展名。 我用 javascript 编写了一个脚本,它倾向于进行正确的缩进,但分配的扩展名不正确。我得到所有文件元素标题的 .dita。这是代码: const fs = require('fs'); const XmlStream = require('xml-stream'); // Create a readable stream from the XML file const stream = fs.createReadStream('input1.xml'); // Create a writable stream to the output text file const outputStream = fs.createWriteStream('output.txt'); // Create a new XML stream parser const xmlParser = new XmlStream(stream); // Function to print headings with proper indentation function printHeadingsToFile(file, indentation = '') { // Calculate the indentation based on the level of the file const levelIndentation = ' '.repeat(parseInt(file.$.level.substr(6)) - 1); // Determine file extension based on child elements const fileExtension = file.file ? 'ditamap' : 'dita'; // Write the heading with indentation to the output file outputStream.write(`${indentation}${levelIndentation}${file.$.heading}.${fileExtension}\n`); // Check if there are nested files if (file.file) { // If nested files exist, recursively print their headings with increased indentation file.file.forEach(nestedFile => { printHeadingsToFile(nestedFile, `${indentation}${levelIndentation}`); }); } } // Event listener for when a new XML element is encountered xmlParser.on('startElement: file', function(element) { // Print headings for each file printHeadingsToFile(element); }); // Event listener for when the parsing ends xmlParser.on('end', function() { console.log('Parsing finished.'); // Close the output stream after finishing writing outputStream.end(); }); // Event listener for any errors during parsing xmlParser.on('error', function(err) { console.error('Error during parsing:', err); // Close the output stream if there is an error outputStream.end(); }); 我在这里得到的输出如下: XYZ1-L1.dita XYZ1-L12.dita XYZ1-L123.dita XYZ1-L123.dita XYZ1-L123.dita XYZ2-L1.dita XYZ2-L1.dita XYZ2-L12.dita XYZ2-L123.dita XYZ1-L123.dita XYZ1-L123.dita 预期输出: XYZ1-L1.ditamap XYZ1-L12.ditamap XYZ1-L123.dita XYZ1-L123.dita XYZ1-L123.dita XYZ2-L1.dita XYZ2-L1.ditamap XYZ2-L12.dita XYZ2-L123.ditamap XYZ1-L123.ditamap XYZ1-L123.dita 找到了使用不同 xml 解析器包的解决方案。 const fs = require('fs'); const sax = require('sax'); // Create a SAX parser const parser = sax.parser(true); // Create a write stream to a text file const outputStream = fs.createWriteStream('output.txt'); // Array to store file attributes let fileAttributes = []; // Event handlers for the SAX parser parser.onopentag = function (node) { // Check if the current node is a <file> element if (node.name === 'file') { // Extract attributes and push them to the array fileAttributes.push(node.attributes); } }; parser.onend = function () { // Parsing ends, log the final output //console.log('File attributes:', fileAttributes); // Function to determine the file extension function getFileExtension(currentLevel, nextLevel) { if (currentLevel < nextLevel) { return '.ditamap'; } else { return '.dita'; } } // Iterate through the fileAttributes array for (let i = 0; i < fileAttributes.length; i++) { const currentFile = fileAttributes[i]; const nextFile = fileAttributes[i + 1]; // Get the level numbers const currentLevel = parseInt(currentFile.level.match(/\d+/)[0]); const nextLevel = nextFile ? parseInt(nextFile.level.match(/\d+/)[0]) : 0; // Get the file extension const extension = getFileExtension(currentLevel, nextLevel); // Indentation based on the level const indentation = ' '.repeat((currentLevel - 1) * 4); // Prepare the text to write const textToWrite = indentation + currentFile.heading + extension + '\n'; // Write the text to the output stream outputStream.write(textToWrite); } // Close the output stream when done outputStream.end(); }; // Read XML file const xmlData = fs.readFileSync('input.xml', 'utf8'); // Parse XML data parser.write(xmlData).close(); 结果输出: L1.ditamap L2.ditamap L3.dita L3.dita L3.dita L1.dita L1.ditamap L2.dita L2.ditamap L3.ditamap L4.ditamap Level5Text.dita

回答 1 投票 0

向仅包含一个节点的循环链表添加一个节点

几周前我才听说链表,现在我开始关注循环链表。问题很简单:在只有一个元素的循环列表中,下一个节点就是它自己,即……

回答 2 投票 0

在 C 中合并两个链表时出现问题

我应该编写一个函数来合并(将一个放在另一个的末尾)两个单链表。用户在控制台输入一串数字,例如:1 2 3 4 0(0表示结束...

回答 2 投票 0

删除链表节点的函数不会在另一个函数中返回修改后的哨兵

这个deleteNode函数之前可以工作,但是minScore函数被设置为返回最大分数而不是最小值。我已经调试了6个小时,似乎当它进入计算时......

回答 1 投票 0

© www.soinside.com 2019 - 2024. All rights reserved.