我有一个 LinkedList
(LinkedList
的自己的代码),里面有 char
。这是完整列表:['a','b','I','d','R','A','7','p']
。
我正在尝试编写一个方法来删除所有非大写字母的字符。运行该方法后,LinkedList
应如下所示 ['I','R','A']
。
但是在运行我的代码之后,我得到了与 return
相同的列表,这个列表:['a','b','I','d','R', 'A','7','p']
.
这是我的方法代码:
public static ListNode copyUpperCase(ListNode head) {
ListNode ptr = head;
while(!isEmpty(ptr.next)){
if(!Character.isUpperCase(ptr.element)){
ptr = ptr.next.next;
//System.out.println(ptr.element);
}
ptr = ptr.next;
}
return head;
}
这是isEmpty()
:
public static boolean isEmpty(ListNode l) {
if ( l == null )
throw new ListsException("Lists: null passed to isEmpty");
return l.next == null;
}
这是ListNode
:
public class ListNode {
public char element;
public ListNode next;
}
我可以看到搜索部分正在运行,但我无法正确删除节点部分,有什么建议吗?
最佳答案
public static ListNode copyUpperCase(ListNode head) {
ListNode ptr = head;
while(!isEmpty(ptr.next)){
if(!Character.isUpperCase(ptr.element)){
ptr.next = ptr.next.next;
//System.out.println(ptr.element);
}
ptr = ptr.next;
}
return head;
}
您需要“更改”列表,所以您只是错过了对元素的赋值,而不是局部变量
然而,这段代码将不起作用,因为它只是分配给下一个元素,而不检查下一个元素是否真的是一个好元素,然后跳到那个元素
编辑:完整的工作代码
class ListNode {
public ListNode(char element,ListNode next ) {
this.element = element;
this.next = next;
}
public char element;
public ListNode next;
void print() {
System.out.print(this.element+",");
if(this.next != null) {
this.next.print();
}
else {
System.out.println("");
}
}
}
public class main {
//Imo you should only check if this elem is a null one, as a null means empty, a null on next only means that it's the last elem, but will still contain data
public static boolean isEmpty(ListNode l) {
return l == null;
}
public static ListNode getNextUpper(ListNode head) {
while(!isEmpty(head)){
if(Character.isUpperCase(head.element)) {
return head;
}
head = head.next;
}
return null;
}
public static ListNode copyUpperCase(ListNode head) {
ListNode newhead = getNextUpper(head);
ListNode temp = newhead;
while(!isEmpty(temp)){
temp.next = getNextUpper(temp.next);
temp = temp.next;
}
return newhead;
}
public static void main(String[] args) {
ListNode t = new ListNode('a' , new ListNode('b' , new ListNode('I', new ListNode('d', new ListNode('R', new ListNode('A', new ListNode('7', new ListNode('p',null))))))));
t.print();
ListNode newt = copyUpperCase(t);
newt.print();
}
}
关于java - 从 LinkedList 中删除 "links"?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36966627/