反向单向链表Java?



我有一个问题,我无法运行这个方法,我想反转单个 Linkedlist 中的节点,我说所有来自 Stackoverflow 的帖子都是关于反向的,但它们与我的代码不同。 有我的代码

public node reverse(node head) {
node p,q;
if(head==null) {
return head;
}
p=head;
q=p.next;
if(q==null) {
return p;
}
q=reverse(q);
p.next.next=p;
p.next=null;
return q;
}public void printList(){
node currentNode = head;
while(currentNode != null){
System.out.print(currentNode.data);
currentNode=currentNode.next;
}
}

主类

public class main {
public static void main(String[] args) {
linkedlist obj = new linkedlist();
obj.insertFirst(1);
obj.insertFirst(2);
obj.insertFirst(3);
obj.insertFirst(4);
obj.insertFirst(5);
obj.reverse(head);  
obj.printList();

请通过那里的代码给我一个解决方案。

反转链表:

class LinkedList {
static Node head;
static class Node {
int data;
Node next;
Node(int d) {
data = d;
next = null;
}
}
/* Function to reverse the linked list */
Node reverse(Node node) {
Node prev = null;
Node current = node;
Node next = null;
while (current != null) {
next = current.next;
current.next = prev;
prev = current;
current = next;
}
node = prev;
return node;
}
// prints content of double linked list
void printList(Node node) {
while (node != null) {
System.out.print(node.data + " ");
node = node.next;
}
}
public static void main(String[] args) {
LinkedList list = new LinkedList();
list.head = new Node(85);
list.head.next = new Node(15);
list.head.next.next = new Node(4);
list.head.next.next.next = new Node(20);
System.out.println("Given Linked list");
list.printList(head);
head = list.reverse(head);
System.out.println("");
System.out.println("Reversed linked list ");
list.printList(head);
}
}

你的代码没有什么意义,也很难让它正确。我建议先采用这样更简单简洁的方法。

public node reverse(node head) {
if(head == null || head->next == mull) {
return head;      
}
node current = head;
node newHead = null;
node previous = null;
while(current != null) {
node nxt = current.next;
current.next = previous;
newHead = current;
previous = current;
current = nxt;
}
return newHead;
}