[英]i can't print the linkedlist elements in reverse order using recursion
我是Java的初學者。我正在實現鏈表中的遞歸以按相反的順序打印元素,但我認為我的代碼中存在語義錯誤,請提前檢查我的代碼(尤其是反向方法)。 輸出:78 30 52發送后,從頭開始您需要插入包裝練習的計數;
public class Linkedlist {
Node head;
public Linkedlist() {
head = null;
}
public void insert(int data) {
Node obj1 = new Node(data);
obj1.next = head;
head = obj1;
}
public void append(int data) {
Node newn = new Node(data);
if (head == null) {
newn.next = null;
head = newn;
return;
}
Node n = head;
while (n.next != null) {
n = n.next;
}
newn.next = null;
n.next = newn;
}
void delete(int data) {
if (head == null) {
return;
} else if (head.data == data) {
head = head.next;
return;
}
Node curr = head;
while (curr.next != null) {
if (curr.next.data == data) {
curr.next = curr.next.next;
}
curr = curr.next;
}
}
void insertAt(int count, int data) {
Node h = head;
if (count == 0) {
this.insert(data);
return;
}
while (h.next != null) {
if (count == 0) {
Node f = new Node(data);
f = h.next;
h = f;
return;
}
count--;
h = h.next;
}
}
public void reverse() {
if (head == null) {
System.out.println("null");
} else {
this.reverseRecursive(head);
}
}
private void reverseRecursive(Node nod) {
if (nod == null) {
return;
}
reverseRecursive(nod.next);
System.out.print(nod.data + " ");
}
class Node {
Node next;
int data;
public Node(int data) {
this.data = data;
}
}
public static void main(String args[]) {
Linkedlist obj = new Linkedlist();
obj.insert(78);
obj.insert(30);
obj.insert(52);
obj.reverse();
System.out.println("send after which item count from head u need to insert");
obj.insertAt(2, 5);
}
}
查看您的代碼,我認為您的Reverse方法沒有任何問題。 它實際上是按相反的順序打印。 讓您煩惱的可能是插入元素的方式。 您的insert()方法實際上是一個堆棧。 (它插入頂部)。 因此,在所有插入之后,head指向52而不是78。因此,在打印時,反向列表顯示為:
78 30 52
另外,您的代碼需要一些格式設置,並且應遵循Java約定。 方法名稱以小寫字母開頭,類名稱以大寫字母開頭。 祝好運 :)
在您的LinkedList中,而不是使用insert方法,該方法在頭部添加元素,請使用方法append將方法添加到LinkedList的末尾,然后調用反向方法。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.