2014-06-05 79 views
0

我有一個類似於List的數據結構,但我不能使用任何內置容器(列表<>等)。我想保留一個「指向指針」又名「尾巴」,指向這個列表的尾部。它應該在C++中這樣:如何在C#中做「指針指針」?

class MyList { 
    Node* head; 
    Node** tail; // tail is just a pointer to the "next" pointer of the end of the list. 
    MyList() { 
    head = null; 
    tail = &head; 
    } 
    bool isEmpty() { 
    return head == null; 
    } 
    void add(int val) { 
    *tail = new Node(); 
    (*tail)->val = val; 
    tail = &((*tail)->next); 
    } 
} 

如何在C#中實現這個?謝謝!

+4

有沒有必要使用指針來做到這一點,引用是足夠的。但是,你爲什麼要這樣做呢?你應該解釋一下你正在試圖解決的問題,因爲你很可能在考慮這個錯誤。將C++轉換爲C#通常是一個糟糕的主意。 'List [List.Count - 1]'有什麼問題?另外,如果你想要一個鏈表,爲什麼不使用內置'LinkedList'? :) – Luaan

+0

不要試圖混合蘋果與橙子 –

+0

啊..我們走了。謝謝。更清晰。 – WhozCraig

回答

1

你說得對,C#不能(安全地)實現一個指針指針。結果像你這樣的可愛代碼是不可能的。這是我能做的最好的。

public class Node { 
    public Node next; 
    public int val; 
} 
class MyList { 
    Node head = null; 
    Node tail = null; 
    public MyList() { } 
    bool isEmpty() { 
    return head == null; 
    } 
    void add(int val) { 
    if (isEmpty()) 
     head = tail = new Node(); 
    else { 
     tail.next = new Node(); 
     tail = tail.next; 
    } 
    tail.val = val; 
    } 
} 

這不壞,是嗎?幾乎完全相同的長度和(我認爲)稍微容易理解。

C++中有強大的功能在C#中不可用,但根據我的經驗,C#是一種效率更高的語言,即使對於像這樣的低級代碼。

如果你有其他一些你認爲不會屈服於這種簡單翻譯的代碼,請發帖,我們會看看我們能做些什麼。

4

如何使用LinkedList代替列表<> ...?

+1

+1爲什麼要重新發明輪子? – WhozCraig

+0

謝謝。但我的例子只是我的問題的抽象,它是相似的,但不一樣。在實際情況下,我無法使用任何內置容器。 – JASON

+4

@JASON - 你想介紹一下你想做什麼的細節,你認爲你不能用內置容器做什麼? – Corak