2013-03-17 36 views
0

我正在學習Ruby,並且正在做一個鏈接列表類。我正在編寫雙向鏈表的刪除方法。我的問題是,如果我通過它的頭節點表示列表,我該如何刪除頭部?看起來Ruby不會讓你指定自變量,所以我不能將調用者的引用改爲下一個節點。一種解決方案是我可以從下一個節點和交​​換引用中複製密鑰,但是通常情況下,Ruby中是否有方法來更改調用者的引用?在Ruby中修改調用對象

class LinkedListNode 

    attr_accessor :next, :previous, :key 

    def initialize(key=nil, next_node=nil, previous=nil) 
     @next = next_node 
     @previous = previous 
     @key = key 
    end 

    def append(key=nil) 
     newnode = LinkedListNode.new(key) 
     seeker = self 
     while seeker.next != nil 
      seeker = seeker.next 
     end 
     newnode.previous = seeker 
     seeker.next = newnode 
    end 

    def delete(key=nil) 
     seeker = self 
     while seeker.key != key 
      return if seeker.next == nil 
      seeker = seeker.next 
     end 
     if seeker.previous != nil 
      if seeker.next != nil 
       seeker.previous.next = seeker.next 
       seeker.next.previous = seeker.previous 
      else 
       seeker.previous.next = nil 
      end 
     else 
      return self = self.next 
     end 
     return seeker = nil 
    end 

    def print 
     seeker = self 
     string = "" 
     while 1 
      if seeker.next == nil 
       string += seeker.key.to_s 
       break 
      else 
       string += seeker.key.to_s + " -> " 
      end 
      seeker = seeker.next 
     end 
     puts string 
    end 
end 

if __FILE__ == $0 
    ll = LinkedListNode.new(1) 
    ll.append(2) 
    ll.append(3) 
    ll.append(4) 
    ll.append(5) 

    ll.print 

    ll.delete(5) 
    ll.print 

    ll.delete(1) 
    ll.print 
end 

回答

0

你不能改變被指向的哪個對象,被調用者(即修改self),但你可以操縱的對象在任何你想要的,因爲你已經想到過。簡短的答案是它不能完成。你可以想出其他方法來模擬它,但我認爲你已經走上了正軌。

0

您需要以不同方式概念化鏈接列表。 LinkedListNode是LinkedList的一個組件,而不是LinkedList本身。像append,delete和print這樣的操作應該放在LinkedList類中,而不是LinkedListNode類中。嘗試從類似

class LinkedList 

    # This one-liner defines a LinkedList::Node with associated constructor 
    # and accessors for the three tags provided. Any tags omitted during 
    # construction will be initialized to nil. 
    Node = Struct.new(:key, :previous, :next) 

    attr_reader :head, :tail 

    def initialize 
    # start with no Nodes in the list 
    @head = @tail = nil 
    end 

    def append(key) 
    # Make the LinkedList tail a new node that stores the key, 
    # points to the prior tail as its previous reference, and 
    # has no next. 
    @tail = Node.new(key, @tail) 
    if @tail.previous # the prior tail was not nil 
     @tail.previous.next = @tail # make the prior tail point to the new one 
    else    # if there wasn't any tail before the list was empty 
     @head = @tail # so the new tail Node is also the head 
    end 
    end 

    # ... 

end