在链表中查找大写并返回带有找到元素的新链表?

时间:2014-04-06 12:43:56

标签: java eclipse algorithm list linked-list

我必须编写一个方法来搜索链表(ListNode,每个listnode加一个char),查找所有大写字符,将它们复制到新的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;
}

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

2 个答案:

答案 0 :(得分:2)

您需要在某处创建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;
}

答案 1 :(得分:2)

扩展@ 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;

}