gpt4 book ai didi

java - Java中反转链表的程序

转载 作者:行者123 更新时间:2023-12-01 12:19:53 25 4
gpt4 key购买 nike

我编写了以下代码,其中方法 rev(list,list) 不起作用。请帮我确定问题所在。

import java.io.*;
public class list
{
int d;
list l;
list()
{
d=0;
l=null;
}

void create()throws IOException
{
int n;// store number of nodes
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter the first data");
this.d=Integer.parseInt(br.readLine());
System.out.println("Enter number of nodes to be made");
n=Integer.parseInt(br.readLine());
list temp;
list ptr=this;
for(int i=1;i<n;i++)
{
temp=new list();
System.out.println("Enter the next data");
temp.d=Integer.parseInt(br.readLine());
temp.l=null;
ptr.l=temp;
temp=null;
ptr=ptr.l;
}
}

void delete(list lst, int n)
{
list ptr=lst;
list ptr1=ptr;
int c=1;
while(c<n)
{
ptr1=ptr;
ptr=ptr.l;
c++;
}
ptr1.l=ptr.l;
ptr.l=null;
ptr=null;
ptr1=null;
}

void insertmid(list lst,int x, int n)
{
list temp=new list();
temp.d=x;
temp.l=null;
list ptr=lst;
int c=1;
while(c<n)
{
ptr=ptr.l;
c++;
}
temp.l=ptr.l;
ptr.l=temp;
}

void rev(list lst,list lst1)
{

lst1=null;
list ptr=new list();

while(lst!=null)
{
ptr =lst;
lst=lst.l;
ptr.l=lst1;
lst1=ptr;

}
}


void display()
{
list ptr=this;

while(ptr!=null)
{
System.out.print(ptr.d+"\t");
ptr=ptr.l;
}
System.out.println();
}

public static void main(String args[])throws IOException
{
list l2=new list();
list l3=new list();

l2.create();
l2.display();
l2.insertmid(l2,14,2);
l2.display();
l2.delete(l2, 3);
l2.display();
l2.rev(l2,l3);
l2.display();

}
}

最佳答案

您应该做的第一件事就是熟悉 Java Naming Conventions因为它会让你的代码更干净、更容易理解。您当前的代码不区分类、方法或变量。

其次,看来您来自 C++ 背景,并且不知道 Java 总是 passes by value

这是您正在做的一件毫无意义的事情:

void rev(list lst,list lst1)
{

lst1=null; // this is pointless, essentially, you are using a passed argument as a local variable.
// ...

下面的代码实际上是等效的:

void rev(list lst)
{

list lst1=null; //just create lst1 right here, don't need to pass it in as a parameter
// ...

现在,我不会清理你的整个代码,但我会给你反向链接列表的算法,你可以将其合并到你的程序中:

public Node reverseList(Node head) {
Node newHead = null; // New head of the reversed list
Node prev, curr, next; // Tracker pointers to previous, current and next node
prev = null;
curr = head;
next = null;
while(curr != null) { // Iterate through the list
next = curr.next; // Remember the next node
curr.next = prev; // Point the current node to the previous
prev = curr; // Update the previous node tracker to the current node
curr = next; // Update the current node tracker to the next node
if(next == null) { // If we reached list end, store the new head
newHead = prev;
}
}
return newHead;
}

关于java - Java中反转链表的程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26761714/

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