-2
これは私のコードです。単一リンクリストがパリンドロームかどうかを確認する
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace LinkedList
{
public class Node
{
public int data;
public Node next;
public Node(int data)
{
this.data = data;
next = null;
}
}
public class MyList
{
public Node head;
public MyList()
{
head = null;
}
public void addNode(int data)
{
if(head == null)
{
head = new Node(data);
}
else
{
Node temp = new Node(data);
Node current = head;
while(current.next != null)
{
current = current.next;
}
current.next = temp;
}
}
public void print()
{
if(head == null)
{
Console.WriteLine("List is already empty!");
}
else
{
Node current = head;
while (current != null)
{
Console.Write("|" + current.data + "|-> ");
current = current.next;
}
Console.WriteLine();
}
}
public void addToStart(int data)
{
if(head == null)
{
head = new Node(data);
}
else
{
Node temp = new Node(data);
temp.next = head;
head = temp;
}
}
public void addSorted(int data)
{
if(head == null)
{
head = new Node(data);
}
else if(data < head.data)
{
addToStart(data);
}
else
{
Node current = head.next;
Node previous = head;
Node temp = new Node(data);
while(current != null)
{
if(data < current.data)
{
previous.next = temp;
temp.next = current;
break;
}
previous = current;
current = current.next;
}
}
}
public void removeLast()
{
if(head == null)
{
Console.WriteLine("List is already empty!");
}
else if(head.next == null)
{
head = null;
}
else
{
Node current = head.next;
Node previous = head;
while(current.next != null)
{
previous = current;
current = current.next;
}
previous.next = null;
}
}
public bool isPalindrome()
{
List<int> arr1 = new List<int>();
int i = 0;
Node current = head;
while (current != null)
{
arr1.Add(current.data);
current = current.next;
i++;
}
int[] arr3 = arr1.ToArray();
int count = i;
int[] arr2 = new int[count];
int j = 0;
for (int x = i - 1; x >= 0; x--)
{
arr2[j] = arr3[x];
}
for (int k = 0; k < count; k++)
{
if (arr3[k] != arr2[k])
{
return false;
}
}
return true;
}
}
class Program
{
static void Main(string[] args)
{
MyList a = new MyList();
a.addNode(1);
a.addNode(2);
a.addNode(5);
a.addNode(2);
a.addNode(1);
a.print();
if(a.isPalindrome())
{
Console.WriteLine("Linked List is Palindrome!");
}
else
{
Console.WriteLine("Linked List is Not Palindrome!");
}
}
}
}
私のコードは、回文機能のために、私はリンクリストで唯一の値を入力する場合を除いて毎回falseを返します。
また、List<int>
の方法が大丈夫かどうかは、私が回文チェックのために必要なので教えてください。
あなたのタイトルをすべて大文字にすることで、より重要になるようにしようとすると、回答が得られにくいことがわかりましたか?あなたが疑問に思っていることは他の誰よりも重要ではないと思います。 – itsme86
デバッガは 'arr2'と' arr3'の値は何であると言いますか?また、入力リストとどのように比較しますか?デバッガのコードを踏んでライブを見ましたか? –
FWIW、タイトルの叫びのためにすべてのダウン投票を受けたと思う。質問そのもののプレゼンテーションは、ここでは初心者から見た多くの質問よりも悪いものではありません。少なくとも実際の[mcve]があります。私はあなたがデバッガでより多くの時間を費やすべきだと思います。 @Kenの前のコメントは、どこを見るかについての大きなヒントを与えています。実際の実装の問題については、 'List'を使用することは過剰です。数えてから配列にまっすぐコピーするのはなぜですか?あるいは、中間オブジェクトを使わずに確認するための再帰的メソッドを書くことができます。 –