【问题标题】:How to reverse my linked list?如何反转我的链表?
【发布时间】:2014-04-17 01:18:30
【问题描述】:

我需要知道如何反转我的链表。

我将发布我的 Node 和 LinkedList 类。另外两个是驱动程序(它创建了我的 TUI 类和我的 TUI 类的实例,它询问用户将哪个单词添加到 LinkedList,然后打印列表并反转它(通过调用 LinkedList 中的 reverse 方法,这就是我需要帮助)

我不知道在我的 LinkedList 中为 reverse 方法写什么

节点类:

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() {

}
}

【问题讨论】:

  • 如果您扫描列表并向后更改所有链接会怎样?
  • 我需要在LinkedList中有reverse方法。
  • 哦,有人赞成这个..
  • 迈克 B,我已经尝试将头部设置为尾部。我尝试了一个while循环(尽管我认为这是要走的路,但我知道我做错了)

标签: java linked-list reverse


【解决方案1】:

这应该可以完成工作。思路是,对于每个链表节点,临时复制其下一个节点,将其设置为上一个节点的下一个,并将上一个节点设置为它。它也可以递归完成。

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;
}

编辑:您还需要更新尾部引用

【讨论】:

  • 是的,谢谢!效果很好。下次我会把它画在一张纸或其他东西上。
猜你喜欢
  • 2012-02-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-10-02
相关资源
最近更新 更多