gpt4 book ai didi

java - 双链表实现回文检查器

转载 作者:行者123 更新时间:2023-12-01 09:23:56 26 4
gpt4 key购买 nike

嗨,我正在尝试实现此代码来检查回文并删除并添加到左侧和右侧。我无法弄清楚如何从列表中删除并添加请帮忙。

public class DLL {

private charNode DLLleft, DLLright;

class charNode {
char data;
charNode left;
charNode right;

public charNode(char D, charNode l, charNode r) {
data=D;
left = l;
right = r;
}
}

public DLL() {
DLLleft= null;
DLLright= null;
}
public void addDLLleft(char data){
charNode temp = new charNode(data, null, DLLleft);
if(DLLleft ==null)
DLLright = temp;
else
DLLleft.left=temp;
DLLleft = temp;
}
public void addDLLright(char data){
charNode temp = new charNode(data, null, DLLright);
if(DLLright == null)
DLLleft = temp;
else
DLLright.right = temp;
DLLright = temp;
}
public char removeDLLright(char data){
charNode temp = DLLright;
while (data == DLLright.data);

}
public void printRtoL(){
charNode temp = DLLright;
while(temp != null){
System.out.println(temp.data);
temp = temp.left;
}
}
public void printLtoR(){
charNode temp = DLLleft;
while(temp != null){
System.out.println(temp.data);
temp = temp.right;
}
}
public void clearDLL(){
DLLleft = null;
DLLright = null;
}
}

这是我到目前为止所拥有的,但我坚持如何从列表中删除并从回文中检查。

最佳答案

使用一种递归方法这将非常简单......但是,让我们玩点乐趣。为了使其更具可读性,我将重命名您的一些变量(我将保留您的方法名称,以便您知道发生了什么)。

public class DLL<E> {

private charNode head;
private charNode tail;
private int size;

private class charNode {
E element;
charNode next;
charNode prev;

public charNode(E element, charNode next, charNode prev) {
this.element = element;
this.next = next;
this.prev = prev;
}
}

public void addDLLleft(E element){
charNode temp = new charNode(element, head, null);
if(head != null ) {
head.prev = temp;
}
head = temp;
if(tail == null) {
tail = temp;
}
size++;
}
public void addDLLright(char data){
charNode temp = new charNode(element, null, tail);
if(tail != null) {
tail.next = temp;
}
tail = temp;
if(head == null) {
head = temp;
}
size++;
}

public E removeDLLleft(){
if (size == 0) throw new NoSuchElementException();
charNode temp = head;
head = head.next;
head.prev = null;
size--;
return temp.element;
}

public E removeDLLright(){
if (size == 0) throw new NoSuchElementException();
Node temp = tail;
tail = tail.prev;
tail.next = null;
size--;
return temp.element;

}

public void printRtoL(){
charNode temp = tail;
while(temp != null){
System.out.println(temp.element);
temp = temp.prev;
}
}

public void printLtoR(){
charNode temp = head;
while(temp != null){
System.out.println(temp.element);
temp = temp.next;
}
}

public void clearDLL(){
DLLleft = null;
DLLright = null;
}

// Necessary
public int size() {
return size;
}
}

关于java - 双链表实现回文检查器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39989601/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com