不使用数组方法反转 LinkedList [英] Reverse a LinkedList WITHOUT using array methods
问题描述
所以,我正在处理一个任务,其中 LinkedListNode 类生成一个链表并将值打印给用户.我应该做的是创建一个 Stack 类来推送"、弹出"和反转链表.问题是,我们无法使用 .push、.pop 或其他任何东西的数组方法.
So, I'm working on an assignment where a LinkedListNode class generates a linked list and prints the values to the user. What I am supposed to do is create a Stack class to 'push', 'pop', and reverse the linked list. The thing is, we are unable to use the array methods of .push, .pop, or anything else.
一天多来,我一直在思考并试图查找要做什么,但不知道从哪里开始.有人可以请我指出正确的方向,让我开始使用推送方法,这样我就可以得到一些牵引力,也许能赶上?
I have been thinking and trying to look up what to do for over a day and have no clue on where to even start. Could someone please point me in the right direction of just getting the push method started so I can get some traction and maybe catch on?
给出的 LinkedListNode 类:
LinkedListNode class given:
class LinkedListNode
attr_accessor :value, :next_node
def initialize(value, next_node=nil)
@value = value
@next_node = next_node
end
end
给出的 Stack 类的起始骨架:
Starting skeleton of Stack class given:
class Stack
attr_reader :data
def initialize
@data = nil
end
# Push an item onto the stack
def push(element)
# IMPLEMENT ME!
end
# Pop an item off the stack.
# Remove the last item that was pushed onto the
# stack and return it to the user
def pop
# IMPLEMENT ME
end
end
我不是想直接询问答案,我只是不知道该去哪里.在此先感谢您的帮助!
I am not trying to ask for the answer straight out, I just can't figure out where to go. Thank you in advance for any help!
推荐答案
您可以使用 Linked List 数据类型而不是数组来实现 Stack.我相信这样的事情会奏效:
You can use the Linked List datatype, rather than an array, to implement a Stack. I believe something like this would work:
def push(element)
if data.nil?
data = LinkedListNode.new(element, nil)
else
data = LinkedListNode.new(element, data)
end
end
def pop
# grab the top piece of data
popped = data.value
# shift the data
data = data.next_node
end
这篇关于不使用数组方法反转 LinkedList的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!