[英]Reversing a singly linked list?
這是我為單鏈表提供的代碼,但是我正在努力完成反向 function。 這是代碼和我在反向 function 的嘗試。 我不斷收到 2 個錯誤,上面寫着“未聲明的變量:節點”和“不兼容的類型:節點無法轉換為鏈接列表”。
class LinkedList
{
Node head;
Node current;
Node previous;
public Object Get()
{
return current != null ? current.GetData() : null;
}
public void Next()
{
if (current != null)
{
previous = current;
current = current.next;
}
}
public void Head()
{
previous = null;
current = head;
}
public void Insert(Object data)
{
Node node = new Node(data);
node.next = current;
if (current == head)
head = node;
else
previous.next = node;
current = node;
}
public void Remove()
{
if (current == null)
throw new RuntimeException("Invalid position to remove");
if (current == head)
head = current.next;
else
previous.next = current.next;
current = current.next;
}
public void Print()
{
for (Head(); Get() != null; Next())
System.out.println(Get());
}
public LinkedList Reverse()
{
Node previous = null;
Node current = node;
Node forward;
while (current != null)
{
forward = current.next;
current.next = previous;
previous = current;
current = forward;
}
return previous;
}
}
還有 class Node: class Node { // 下一個節點的公共引用 public Node next;
// Private data field
Object data;
Node(Object data)
{
this.data = data;
}
public Object GetData()
{
return data;
}
}
這是主要的 function: class Test { public static void main(String args[]) { // 創建一個單鏈表 () Linked_list = new
// adding node into singly linked list
linked_list.Insert(Integer.valueOf(10));
linked_list.Next();
linked_list.Insert(Integer.valueOf(11));
linked_list.Next();
linked_list.Insert(Integer.valueOf(12));
// printing a singly linked
linked_list.Print();
// reversing the singly linked list
linked_list.Reverse();
// printing the singly linked list again
linked_list.Print();
}
}
這是簡單的解決方案:
public class ListReverser {
Node<Integer> reverse(Node head) {
Node current = head;
while(current.getNext() != null) {
Node next = current.getNext();
current.setNext(next.getNext());
next.setNext(head);
head = next;
}
return head;
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.