簡體   English   中英

反轉鏈接列表未按預期工作

[英]Reversing a Linked List not working as expected

我目前正在嘗試反轉鏈接列表,但遇到了無法正確打印的意外問題。 當我嘗試訪問鏈表的值時,我得到一個錯誤。 我將不勝感激專家的眼睛,看看我錯過了什么。 提前致謝。

public class SinglyLinkedList<E> implements Cloneable, Iterable<E>, List<E> {
    //---------------- nested Node class ----------------

    /**
     * Node of a singly linked list, which stores a reference to its
     * element and to the subsequent node in the list (or null if this
     * is the last node).
     */
    private static class Node<E> {
        private E data;  // reference to the element stored at this node

        private Node<E> nextNode; 

        
        //methods for accessing variables

        public Node<E> getNextNode() { return nextNode; }

        public E getData() { return data; }

        // Modifier methods
        public void setNext(Node<E> n) { nextNode = n; }
        public void setData(E n) { data = n; }
        public Node(E e, Node<E> n) {
            nextNode = n;
            data = e;
        }

        // reference to the subsequent node in the list// TODO
    } //----------- end of nested Node class -----------

    // instance variables of the SinglyLinkedList
    private int size = 0; // number of nodes in the list
    private Node<E> head = null; // head node of the list (or null if empty)

    public SinglyLinkedList() {
    }              // constructs an initially empty list

    // access methods

    /**
     * Returns the number of elements in the linked list.
     *
     * @return number of elements in the linked list
     */
public void addFirst(E e) {
        head = new Node<E>(e, head); // create the new node and link new node
        size++;
    }
    /**
     * Produces a string representation of the contents of the list.
     * This exists for debugging purposes only.
     */
    public String toString() {
        StringBuilder temporaryString = new StringBuilder();
        temporaryString.append("[");
        for(Iterator<E> iterator = iterator(); iterator.hasNext();){
            temporaryString.append(iterator.next()).append(", ");
        }
        temporaryString.deleteCharAt(temporaryString.length() - 1);
        temporaryString.deleteCharAt(temporaryString.length() - 1);
        temporaryString.append("]");
        return temporaryString.toString();
    }

    private class SinglyLinkedListIterator implements Iterator<E> {
        private Node<E> current;
        public SinglyLinkedListIterator() {
            current = head;
        }
        @Override
        public boolean hasNext() {
            return current != null;
        }

        @Override
        public E next() {
            if(!hasNext()) throw new RuntimeException("No such element");

            E res = current.getData();
            current = current.getNextNode();
            return res;
        }
    }

    public Iterator<E> iterator() {
        return new SinglyLinkedListIterator();
    }

反向鏈表方法:

    public Node<E> reverseLinkedList(SinglyLinkedList sll) {
        Node<E> previous = null;
        Node<E> current = sll.head;
        while (current != null) {
            Node<E> nextElement = current.getNextNode();
            current.setNext(previous);
            previous = current;
            current = nextElement;
        }
        return previous;
    }

主要方法:

public static void main(String[] args) {
        SinglyLinkedList<Integer> sll2 = new SinglyLinkedList<Integer>();
        sll2.addFirst(1);
        sll2.addFirst(2);
        sll2.addFirst(3);

System.out.println(sll2.toString());
        sll2.reverseLinkedList(sll2);
System.out.println(sll2.toString());
    }

output:

[3, 2, 1]
//i should expect to get 1,2,3
[3]

當您在reverseLinkedList function 中對給定的鏈表進行變異(“重新布線”)時,您實際上並沒有生成新的鏈表。 所以讓它返回一些東西實際上是矛盾的。 要么它應該返回一個全新的鏈表而不改變給定的鏈表,要么它應該改變給定的鏈表而不返回任何東西。

從您的main代碼中,我看到您實際上希望改變給定的鏈表,因為您不使用返回的值並基於sll打印結果。 因此,使您的 function 成為void的,並刪除return語句。

現在的核心問題是您永遠不會更改head成員:它仍然引用過去是列表中的第一個節點,但現在是最后一個。 您應該將該節點分配給以前是尾節點的head

所以 function 中的最后一條語句應該是:

sll.head = previous;

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM