【发布时间】:2020-06-25 11:11:16
【问题描述】:
我让用户输入了一个存储在变量“word”中的字符串。我现在想将此存储的变量添加到链表中。我试过使用
LinkedList<string>.Add(word);
要将变量添加到链接的 this 但它不起作用并返回错误“非静态字段、方法或属性 'LinkedList.Add(string)”需要对象引用”
我假设它与我的链接列表有关,但我不确定。
任何关于这个问题的帮助或想法都会很棒。
using System;
using System.Collections.Generic;
using System.Text;
namespace project
{
public class LinkedList<TData>
{
private Node<TData> head;
private int count;
public LinkedList(string word)
{
this.head = null;
this.count = 0;
}
public bool Empty
{
get { return this.count == 0; }
}
public int Count
{
get { return this.count; }
}
public TData this[int index]
{
get { return this.Get(index); }
}
public TData Add(int index, TData data)
{
if (index < 0)
throw new ArgumentOutOfRangeException("Index: " + index);
if (index > count)
index = count;
Node<TData> current = this.head;
if (this.Empty || index == 0)
{
this.head = new Node<TData>(data, this.head);
}
else
{
for (int i = 0; i < index - 1; i++)
{
current = current.Next;
current.Next = new Node<TData>(data, current.Next);
}
}
count++;
return data;
}
public TData Add(TData data)
{
return this.Add(count, data);
}
public TData Remove(int index)
{
if (index < 0)
throw new ArgumentOutOfRangeException("Index: " + index);
if (this.Empty)
return default(TData);
if (index >= this.count)
index = count - 1;
Node<TData> current = this.head;
TData result;
if (index == 0)
{
result = current.Data;
this.head = current.Next;
}
else
{
for (int i = 0; index < index - 1; i++) ;
current = current.Next;
result = current.Next.Data;
current.Next = current.Next.Next;
}
count--;
return result;
}
public void Clear()
{
this.head = null;
this.count = 0;
}
public int IndexOf(TData data)
{
Node<TData> current = this.head;
for (int i = 0; i < this.count; i++)
{
if (current.Data.Equals(data))
return i;
current = current.Next;
}
return -1;
}
public bool Contains(TData data)
{
return this.IndexOf(data) >= 0;
}
public TData Get(int index)
{
if (index < 0)
throw new ArgumentOutOfRangeException("Index: " + index);
if (this.Empty)
return default(TData);
if (index >= this.count)
index = this.count - 1;
Node<TData> current = this.head;
for (int i = 0; i < index; i++)
current = current.Next;
return current.Data;
}
}
}
using System;
using System.Collections.Generic;
using System.Text;
namespace project
{
public class Node<TData>
{
private Node<TData> next { get; set; }
public Node(TData data, Node<TData> next)
{
this.Data = data;
this.next = next;
}
public TData Data { get; set; }
public Node<TData> Next
{
get { return this.next; }
set { this.next = value; }
}
}
}
using System;
using System.Collections.Generic;
using System.Runtime.CompilerServices;
namespace project
{
class Program
{
static void Main(string[] args)
{
string word;
Console.WriteLine("Please enter a word");
word = Console.ReadLine();
Console.WriteLine("You typed: " + word);
Console.ReadKey();
var list = new LinkedList<string>(word);
LinkedList<string>.Add(word);
}
}
}
【问题讨论】:
标签: c# linked-list nodes user-input