![](/img/trans.png)
[英]Returning LinkedList of uppercase Characters when given a LinkedList
[英]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.