繁体   English   中英

在链表中找到大写字母并返回包含找到的元素的新链表?

[英]Finding uppercase in linkedlist and returning new linkedlist with found elements?

我必须编写一种方法来搜索链表(ListNode,每个listnode共包含一个字符),查找所有大写字符,将它们复制到新的ListNode并返回新的ListNode。 到目前为止,这是我的代码,但未通过JUnit测试(由教授提供)。

这是列表节点:

public class ListNode {
    public char element;
    public ListNode next;

}

这是我写的方法,似乎不起作用:

 public static ListNode copyUpperCase(ListNode head) {

    ListNode newListNode = mkEmpty();
    if(head == null){
        throw new ListsException("Lists: null passed to copyUpperCase");
    }else{
        char[] sss = toString(head).toCharArray();
        for(int i = 0; i < sss.length ; i++ )
                if(Character.isUpperCase(sss[i])){
                    newListNode.element = sss[i];       
                }
                newListNode = newListNode.next;
        }           
    return newListNode;
}

代码是什么? 为什么会失败?

您需要在某处创建newListNode.next。 我在提供的代码段中看不到它。 尝试更改您的方法,例如:

 public static ListNode copyUpperCase(ListNode head) {

    ListNode newListNode = mkEmpty(); 
    ListNode newHead = newListNode;   //KEEP HEAD OF NEW LINKED LIST
    if(head == null){
        throw new ListsException("Lists: null passed to copyUpperCase");
    }else{
        char[] sss = toString(head).toCharArray();
        for(int i = 0; i < sss.length ; i++ )
            if(Character.isUpperCase(sss[i])){
                newListNode.element = sss[i];
                newListNode.next = mkEmpty();   //CREATE NEW INSTANCES INSIDE LOOP
                newListNode = newListNode.next; //MOVING FORWARD TO NEXT NODE, newListNode is the last node of new linked list
            }
    }
    return newHead;
}

扩展@enterbios的答案(对他来说为+1),请尝试以下操作:

public static ListNode toUpperCase(ListNode head) {
    if (head == null)
        throw new ListsException("Lists: null passed to copyUpperCase");

    ListNode newHead = null;
    ListNode current = null;

    char[] sss = toString(head).toCharArray();

    for (int i=0; i<sss.length; i++) {
        if (Character.isUpperCase(sss[i])) {
            if (current == null) {
                current = mkEmpty();
                newHead = current;
            } else {
                current.next = mkEmpty();
                current = current.next;
            }
            current.element = sss[i];
        }
    }
    return newHead;

}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM