----题目开始----
实现一个链表,要求各个节点的Name都不重复,若试图增加重复节点,就抛出异常,填写下面的Append方法和Remove方法的代码。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace NodeTest
{
class Program
{
static void Main(string[] args)
{
Link link = new Link();
link.Append("1", 1);
link.Append("2", 2);
link.Append("3", 3);
link.Print();
Console.WriteLine();
link.Remove("2");
link.Print();
Console.ReadKey();
}
}
class Node
{
public string Name { get; set; }
public int Score { get; set; }
public Node Next { get; set; }
}
class Link
{
public Node Head
{
get { return m_nodeHead; }
}
public void Append(string strName, int iScore)
{
//Add a node: implement your code here
Node _node = m_nodeHead;
Node _preNode = null;
while (_node != null && _node.Name != strName)
{
_preNode = _node;
_node = _node.Next;
}
if (_node != null)
{
throw new Exception(strName + "已存在");
}
else
{
_node = new Node { Name = strName, Score = iScore, Next = null };
_preNode.Next = _node;
}
}
public void Remove(string strName)
{
//Delete a node: implement your code here
Node _delNode = m_nodeHead;
Node _preNode = null;
while (_delNode != null && _delNode.Name != strName)
{
_preNode = _delNode;
_delNode = _delNode.Next;
}
if (_delNode != null)
{
_preNode.Next = _delNode.Next;
}
}
public void Print()
{
Node _node = m_nodeHead;
while (_node != null)
{
Console.Write(_node.Name + " -> ");
_node = _node.Next;
}
}
private Node m_nodeHead = new Node()
{
Name = "_HeadNode",
Score = 0,
Next = null
};
}
}