并且实现添加,删除节点的功能
时间: 2023-05-11 21:03:20 浏览: 52
可以使用链表来实现添加和删除节点的功能。链表是一种数据结构,它由一系列节点组成,每个节点包含一个数据元素和一个指向下一个节点的指针。在链表中,可以通过修改指针来添加或删除节点。以下是一个简单的链表实现:
```lua
-- 定义节点
local Node = {}
Node.__index = Node
function Node:new(data)
local node = {}
setmetatable(node, Node)
node.data = data
node.next = nil
return node
end
-- 定义链表
local LinkedList = {}
LinkedList.__index = LinkedList
function LinkedList:new()
local list = {}
setmetatable(list, LinkedList)
list.head = nil
return list
end
function LinkedList:add(data)
local node = Node:new(data)
if not self.head then
self.head = node
else
local current = self.head
while current.next do
current = current.next
end
current.next = node
end
end
function LinkedList:remove(data)
if not self.head then
return
end
if self.head.data == data then
self.head = self.head.next
return
end
local current = self.head
while current.next do
if current.next.data == data then
current.next = current.next.next
return
end
current = current.next
end
end
```
使用这个链表,可以通过调用 `add` 方法来添加节点,调用 `remove` 方法来删除节点。例如:
```lua
local list = LinkedList:new()
list:add(1)
list:add(2)
list:add(3)
list:remove(2)
```
这样就会得到一个包含 1 和 3 两个节点的链表。
相关推荐
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)