iT邦幫忙

0

removeItem 填入問題?

using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ConsoleApp1
{
class Program
{
public class Node
{
public string data = "";
public Node next = null;
public Node(string item)
{
data = item;
}
}

    static Node head = new Node("");
    static Node prev = head;

    static void Main(string[] args)
    {
        String[] words2 = {"The", "QUICK", "BROWN", "FOX", "jumps",
                     "over", "the", "lazy", "dog" };
        for (int i = 0; i < words2.Length; i++)
        {
            addItem(words2[i]);
        }
        printLinkedList(head);
        Console.ReadLine();

    }

    public static void addItem(string item)
    {
        Node current = head.next;
        Node prev = head;
        Node newNode = new Node(item);

        while (true)
        {
            if (current == null)
            {
                current = newNode;
                prev.next = current;
                break;
            }
            else if (current.next != null && current.data[0] > item[0])
            {
                prev.next = newNode;
                newNode.next = current;
                break;
            }
            else
            {
                prev = current;
                current = current.next;

            }
        }

    }

    public static void removeItem(string item)
    {

    }

    public static void printLinkedList(Node list)
    {
        Node current = list;
        while (current.next != null)
        {
            current = current.next;
            Console.WriteLine(current.data + " ");
        }
    }
}

}

1 個回答

0
bantime
iT邦新手 5 級 ‧ 2021-03-08 11:29:58
public static void removeItem(string item)
{
    var current = head.next;
    var prev = head;
    while (current != null && current.data != item)
    {
        prev = current;
        current = current.next;
    }
    prev.next = null;
}

我要發表回答

立即登入回答