2014-02-26 39 views
-1

我試過鏈接列表操作。我可以在列表中添加/刪除節點。但我無法更新列表中的節點值。更新C#中鏈接列表中的節點值

我已經刪除了當前節點的值。所以當我刪除該值時,該節點是否也會被刪除?或者節點仍然可用我可以更新它的值嗎?

這裏是我的代碼

static void Main(string[] args) 
{ 
    string[] words = { "the", "fox", "jumped", "over", "the", "dog" }; 
    LinkedList<string> sentence = new LinkedList<string>(words); 

    // sentence.RemoveFirst(); 
    sentence.AddFirst("today"); 
    LinkedListNode<string> current = sentence.Find("jumped"); 
    sentence.AddAfter(current, "XXX"); 

    LinkedListNode<string> mark1 = current.Previous; 
    sentence.AddAfter(mark1, "ZZZ"); 
    sentence.Remove(current.Value); 
    // I have removed the current's value 

    foreach (string s in sentence) 
    { 
     Console.WriteLine(s); 
    } 

    Console.ReadLine(); 
} 
+0

爲什麼將此標記爲ASP.NET? –

+1

爲什麼你無法更新值? 'current.Value =「sth」'不起作用嗎? – decPL

+0

刪除並不刪除一個值,它刪除一個節點搜索它的值 – Mark

回答

2

你並不需要更換節點,只是改變其值

sentance.Find("jumped").Value = "over" 

...

static void Main(string[] args) 
{ 
    string[] words = { "the", "fox", "jumped", "over", "the", "dog" }; 
    LinkedList<string> sentence = new LinkedList<string>(words); 

    sentance.Find("jumped").Value = "over" 

    foreach (string s in sentence) 
    { 
     Console.WriteLine(s); 
    } 

    Console.ReadLine(); 
} 
+0

它給出一個空引用異常 – tarzanbappa

+0

,因爲你刪除了節點。評論線'sentence.Remove(current.Value);'那麼它不會拋出異常 – Mark

+1

@tarzanbappa你正在尋找一個已經被刪除的值? –

1

您正在使用LinkedList<T>.Remove刪除整個節點的方法,不只是清除值。請參閱MSDN