0

所以我正在制作一个链表,在我的插入中,我需要保持它的顺序。因此,如果我要通过此插入从根遍历链表到它的踪迹-->

Insertion: 1 2 3 

它应该输出-->

Output: 1 2 3

到目前为止,我在下面有这段代码。这段代码所做的就是反向输出我的插入。所以它打印->

3
2
1

我希望程序通过修改我的 addLast() 方法来保持其插入顺序。所以当我打印我的链接列表时,它的输出方式与我插入它的方式相同。

public class LinkedListMeth 
{
  public static void main(String[] args) 
  {
     FirstLinkedList list = new FirstLinkedList();
     list.addLast(1);
     list.addLast(2);
     list.addLast(3);
     list.traverseLast();
 }
}

class FirstLinkedList
{
private class Node           
   {
      private Node next;
      private int data;
   }

   private Node last = null; 

  public void addLast(int d)
   {
       Node newNode = new Node();
       newNode.data = d;
       newNode.next = last;
       last = newNode;  
   }

    public void traverseLast()
   {
       Node head = last;
       while (head != null)

       {
           System.out.println(head.data);
           head = head.next;
       }
   }
4

2 回答 2

0

如果您想坚持当前的确切设计,那么以从头到尾的顺序打印列表的一种选择是使用递归,如下所示:

public void printFirstLinkedList(Node node) {
    if (node == null) return;

    printFirstLinkedList(node.next);

    System.out.print(node.data + " ");

    return;
}

printFirstLinkedList(yourList.last);
于 2018-12-06T05:25:25.790 回答
0

您应该保留链表的根以便按插入顺序遍历。

这是您的代码的编辑版本:

class FirstLinkedList {
    private class Node {
        private Node next;
        private int data;
    }

    private Node root = null;
    private Node last = null;

    public void addLast(int d) {
        Node node = new Node();
        node.data = d;
        if (root == null) {
            root = node;
            root.next = last;
            last = root;
        } else {
            last.next = node;
            last = last.next;
        }
    }

    public void traverseLast() {
        Node head = root;
        while (head != null) {
            System.out.println(head.data);
            head = head.next;
        }
    }
}

输出是:

1
2
3
于 2018-12-06T05:49:27.823 回答