我有一个问题插入一个新的对象到链表。我使用了一个名为Insert的自定义方法,该方法接受对象类型和应该放置对象的索引。然而,当我插入对象时,列表没有更新。知道为什么吗?
列表:
GenericLinkedList<string> bet = new GenericLinkedList<string>();
bet.Add("a");
bet.Add("b");
bet.Add("c");
bet.Add("d");
//bet.Remove();
bet.Insert("x", 2);
泛型链表类:
public class GenericLinkedList<T> where T : IComparable<T>
{
public GenericLinkedList()
{
count = 0;
head = null;
}
#region Nested Node Class
private class Node<T>
{
private T data;
public T Data
{
get { return data; }
set { data = value; }
}
private Node<T> next;
public Node<T> Next
{
get { return next; }
set { next = value; }
}
public Node<T> Previous { get; set; }
public Node(T obj_t)
{
next = null;
data = obj_t;
}
public Node()
{
next = null;
}
}
#endregion
private Node<T> head;
private Node<T> tail;
private int count;
public int Count
{
get
{
int num;
if (count < 0)
num = 0;
else {
num = count;
}
return num;
}
}
}
插入方法: public void Insert(T data, int index)
{
Node<T> replacedItem = new Node<T>();
Node<T> newItem = new Node<T>(data);
if (head == null)
{
head = new Node<T>(data);
tail = head;
}
else
{
Node<T> current = head;
Node<T> tempNode = new Node<T>();
if (index > 0 && index <= count + 1)
{
int c = 0;
while (current != null)
{
if (c == index)
{
tempNode = current;
current = newItem;
current.Next = tempNode;
}
else
{
current = current.Next;
}
c++;
}
}
count++;
}
}
Add方法:
public void Add(T data)
{
count++;
if (head == null)
{
head = new Node<T>(data);
tail = head;
}
else
{
tail.Next = new Node<T>(data);
tail.Next.Previous = tail;
tail = tail.Next;
}
}
需要在case head为null时添加count++。此外,count++应该放在if(index>0&&index<=count+1)
public void Insert(T data, int index)
{
Node<T> replacedItem = new Node<T>();
Node<T> newItem = new Node<T>(data);
if (head == null)
{
head = new Node<T>(data);
tail = head;
count++;
}
else
{
Node<T> current = head;
Node<T> tempNode = new Node<T>();
if (index > 0 && index <= count + 1)
{
int c = 0;
while (current != null)
{
if (c == index)
{
tempNode = current;
current = newItem;
current.Next = tempNode;
}
else
{
current = current.Next;
}
c++;
}
count++;
}
}
}
您没有正确地在Insert
方法中添加新项
在这个地方
tempNode = current; // save pointer to current item
current = newItem; // save in current new item
current.Next = tempNode; //set next to counter
但是你没有改变前一个元素的链接,所以当你再次从头部开始时,你就会错过你添加的项目。
你需要把这段代码改成
public void Insert(T data, int index)
{
Node<T> replacedItem = new Node<T>();
Node<T> newItem = new Node<T>(data);
if (head == null)
{
head = new Node<T>(data);
tail = head;
count++;
}
else
{
Node<T> current = head;
Node<T> tempNode = new Node<T>();
if (index > 0 && index <= count + 1)
{
int c = 0;
while (current != null)
{
if (c == index)
{
tempNode = current;
current = newItem;
//update link from previous element
if(tempNode.Previous != null)
tempNode.Previous.Next = current;
current.Next = tempNode;
current.Previous = tempNode.Previous;
tempNode.Previous = current;
count++;
break;
}
else
{
current = current.Next;
}
c++;
}
}
}
}