使用 listIterator 遍历和替换 Char 值的双向链表

Traversing and Replacing an Doubly-Linked List of Char values using a listIterator

我需要遍历一个双向链表的字符。我需要用 '!' 替换列表中的每个大写 'Y'之后,向后遍历,在创建的同一列表迭代器中将每个 'M' 替换为 ' '。如果你需要更多关于这个问题的背景信息,我会添加更多,但现在这不是很长的解释。

到目前为止我的代码:

public static void main(String[] args)
{
    KWLinkedList<Character> list = new KWLinkedList<Character>() ;
    String linkString = "ZekqmDXJGfaos3MPaSl8p1La.9rXEt43a=Cn#Ds72Y";

    for(int i = 0;  i < linkString.length();i++)
    {
        list.add(linkString.charAt(i));
    }

    ListIterator myIterator = list.listIterator(0) ;

    int i = 0;
    while(!myIterator.hasNext())
    {


        myIterator.next();
        if(myIterator.equals('Y'))
        {
            list.set(list.get(i), 'Y' );
            i = list.get(0);
        }
        if(myIterator.equals('M'))
        {
            list.set(list.get(i - 1), ' ');

        }
        i++;
    }

    System.out.println(list.toString()); // just to see what comes out

要使用 ListIterator to traverse forward and replace some items, using the set() 方法:

ListIterator<Character> iter = list.listIterator();
while (iter.hasNext()) {
    char c = iter.next(); // gets next value and auto-unboxes the Character to a char
    if (c == 'A')         // primitives are compared using `==`
        iter.set('B');    // auto-boxes the char literal to a Character and replaces the value
}

此时迭代器在链表的末尾,所以可以用它向后遍历:

while (iter.hasPrevious()) {
    char c = iter.previous(); // gets previous value, ie. moves backwards
    if (c == 'C')
        iter.set('D');
}

将您的尝试与 Andreas 解决方案相结合

public static void main(String[] args) {
    LinkedList<Character> list = new LinkedList<>();
    String linkString = "ZekqmDXJGfaos3MPaSl8p1La.9rXEt43a=Cn#Ds72Y";

    for (int i = 0; i < linkString.length(); i++) {
        list.add(linkString.charAt(i));
    }

    ListIterator<Character> myIterator = list.listIterator(0);

    while (myIterator.hasNext()) {
        char c =  myIterator.next();
        if (c == 'Y') {
            myIterator.set('!');
        }
    }
    while (myIterator.hasPrevious()) {
        char c = myIterator.previous();
        if (c == 'M') {
            myIterator.set(' ');
        }
    }

    System.out.println(list.toString()); // just to see what comes out
}

输出如下所示
[Z, e, k, q, m, D, X, J, G, f, a, o, s, 3, , P, a, S, l, 8, p, 1, L, a, ., 9, r, X, E, t, 4, 3, a, =, C, n, #, D, s, 7, 2, !]