gpt4 book ai didi

python - 将 n 个值插入一个空的双向链表(伪代码)

转载 作者:塔克拉玛干 更新时间:2023-11-03 05:14:00 25 4
gpt4 key购买 nike

有人可以帮我验证我的伪代码是否正常工作,以便提供的函数将 n 个数字附加到列表中吗?

我在第一年的数据科学作业中需要帮助。

我们正在学习数据结构和双向链表。我理解我认为的双向链表背后的逻辑,但是我很难用伪代码编写发生的事情。

"Assignment 1: Let the list S be empty as a start. Now input n (natural numbers, e.g.: 1, 2, 3 ...) one at the time. When the last number of n is placed into the list, the list will be a sorted list containing the n numbers. Describe why we'll get a sorted n number in O(n^2) time."

我的作业答案写在下面,我真的不确定它是否正确。

// Our nodes will consist of 3 cells in each object.
// key = a number (int)
// prev = address pointer to previous node
// next = address pointer til next node

// This function creates an empty list
function emptyList()
L = new List{head = nil, size = 0}
return L

// This function creates a node.
function makeNode(val)
node = new Node{prev = NIL, key = val, next = NIL}
return node

// This function inserts n amount of nodes to an empty list
function InsertNodes(n)

// Create an empty list, S.
emptyList()

// Initiate the first node
S.head = makeNode(1)

for i = 2 to n-1

prevNode = makeNode(i-1)
newNode = makeNode(i)

while newNode.prev == NIL do

// connect addresses of nodes
prevNode.next = newNode.prev
newNode.prev = prevNode.next

类(class)是关于算法和离散数学的

最佳答案

// Our nodes will consist of 3 cells in each object.
// key = a number (int)
// prev = address pointer to previous node
// next = address pointer til next node

// This function creates an empty list
function emptyList()
L = new List{head = nil, size = 0}
return L

// This function creates a node.
function makeNode(val)
node = new Node{prev = NIL, key = val, next = NIL}
return node

// This function inserts n amount of nodes to an empty list
function InsertNodes(n)

// Create an empty list, S.
emptyList()

// Initiate the first node
S.head = makeNode(1)

//tail keeps the last node
tail = head
for i = 2 to n

tail.next = makeNode(i)
tail.next.prev = tail
tail = tail.next

关于python - 将 n 个值插入一个空的双向链表(伪代码),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52521728/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com