Java 反向单链表
我尝试恢复单链接列表,如下所示:Java 反向单链表,java,linked-list,Java,Linked List,我尝试恢复单链接列表,如下所示: public class MutableLst<T> { public T current; public MutableLst<T> next; private MutableLst(T current){ this.current = current; } public static <T> MutableLst<T> create(T current
public class MutableLst<T> {
public T current;
public MutableLst<T> next;
private MutableLst(T current){
this.current = current;
}
public static <T> MutableLst<T> create(T current){
return new MutableLst<T>(current);
}
public void reverse(){
MutableLst<T> newNext = null;
MutableLst<T> nxt = next;
next = newNext;
while(nxt != null) {
newNext = this; //<------- cycle is here
current = nxt.current;
next = newNext;
nxt = nxt.next;
}
}
公共类MutableLst{
公共电流;
下一步为公共可变LST;
专用可变LST(T电流){
这个电流=电流;
}
公共静态可变LST创建(T当前){
返回新的可变LST(当前);
}
公共无效反向(){
MutableLst newNext=null;
MutableLst nxt=next;
next=newNext;
while(nxt!=null){
newNext=this;//您只是在反转列表,因此我不知道您为什么要对“this”对象执行某些操作。无论如何,我认为您应该使用以下方法:
我会使用递归,如下所示:
public void reverse(MutableLst<T> previous){
if (this.current.next !== null) {
this.next.reverse(this);
}
this.next = previous;
}
public void reverse() {
reverse(null);
}
public void reverse(MutableLst-previous){
if(this.current.next!==null){
这个。下一个。反转(这个);
}
this.next=先前;
}
公共无效反向(){
反向(空);
}
您需要将reverse调到列表的最前面。关于您的具体问题,您正在更改下一个问题,然后才有机会使用它。您可能希望改为执行以下操作:
public void reverse(){
MutableLst<T> previous = null;
MutableLst<T> currentItem = this;
MutableLst<T> nxt = null;
while(currentItem != null) {
nxt = currentItem.next;
currentItem.next = previous;
previous = currentItem;
currentItem = nxt;
}
}
public void reverse(){
MutableLst-previous=null;
MutableLst currentItem=此项;
MutableLst nxt=null;
while(currentItem!=null){
nxt=当前项。下一步;
currentItem.next=上一个;
前一项=当前项;
currentItem=nxt;
}
}
你的代码的问题是你从来没有给next赋值。这是我对你的问题的迭代解决方案。另外,为了让你自己更容易理解,我建议使用一个引用链接列表开头的标题
public void reverse() {
MutableLst<T> prev = null;
MutableLst<T> curr = head;
MutableLst<T> next = null;
while (curr != null) {
next = curr.next;
curr.next = prev;
prev = curr;
curr = next;
}
}
head = prev;
public void reverse(){
MutableLst prev=null;
可变电流=水头;
MutableLst next=null;
while(curr!=null){
下一个=当前下一个;
当前下一个=上一个;
上一次=当前;
curr=next;
}
}
头=上一个;
我认为代码不会进入while循环,因为在您展示给我们的代码中,您从未为next赋值。@MarioSantini会,就在while循环之前为什么要更新值本身(current
)?只需将每个节点重新链接到它的前一个节点,但它的前一个节点是…还是我遗漏了什么?对于下一个节点,它是,但在循环结束时,下一个this
应该是空的,不是吗?因为它现在已反转,所以如果它是第一个节点,它现在将是最后一个。我只需要重新链接当前列表以进行反转,可以吗创建双向链表?然后,您可以将对对象的所有引用放在该链表中。然后清除当前链表,并按相反顺序在临时链表中循环,将元素添加到所需的链表中。