2014-04-17 29 views
1

我需要知道如何反轉我的鏈表。如何反轉我的鏈接列表?

我會發布我的節點和LinkedList類。另外兩個是驅動程序(它創建了我的TUI類的實例和我的TUI類,它向用戶詢問將哪個單詞添加到LinkedList,然後打印列表並反轉它(通過調用LinkedList中的reverse方法,這是我需要的幫助)

我不知道在我的LinkedList反向方法寫

節點類:

public class Node { 

private String data; 
private Node next; 

public Node(String data, Node next) { 
    this.data = data; 
    this.next = next; 
} 

public Node(String data) { 
    this.data = data; 
    this.next = null; 
} 

public String getData() { 
    return this.data; 
} 
public Node getNext() { 
    return this.next; 
} 

public void setNext(Node nextNode) { 
    this.next = nextNode; 
} 

public String toString() { 
    return this.data; 
} 
} 

鏈表類:

public class LinkedList { 

private Node head; 
private Node tail; 

public LinkedList() { 
    this.head = null; 
    this.tail = null; 
} 

public void prepend(String data) { 
    Node newNode = new Node(data, this.head); 
    if (this.head == null) { 
     this.head = newNode; 
     this.tail = newNode; 
    } else { 
     this.head = newNode; 
    } 
} 

public void printList() { 
    Node current = this.head; 

    while (current != null) { 
     System.out.println(current.getData()); 
     current = current.getNext(); 
    } 
} 

public void append(String data) { 
    Node newNode = new Node(data); 

    if (this.head == null) { 
     this.head = newNode; 
     this.tail = newNode; 
    } else { 
     this.tail.setNext(newNode); 
     this.tail = newNode; 
    } 
} 

public void reverse() { 

} 
} 
+0

如果你掃描列表,並改變所有的鏈接倒退? – Leo

+0

我需要在LinkedList中有相反的方法。 – user3241721

+3

哦,有人upvoted這個.. –

回答

2

這應該可以完成這項工作。這個想法是,對於每個列表節點,臨時複製其下一個節點,將其設置到前一個節點旁邊,並將其前一個節點設置爲它。它也可以遞歸地完成。

public void reverse() { 
    Node prev = null; 
    Node current = head; 
    while (current != null) { 
     Node next = current.getNext(); 
     current.setNext(prev); 
     prev = current; 
     current = next; 
    } 
    this.head = prev; 
} 

編輯:您還需要更新尾參考

+0

是的,謝謝你!很棒。下次我會在一張紙或其他東西上畫出來。 – user3241721