通过链接堆栈反转单链表

时间:2015-10-02 02:54:07

标签: java stack reverse singly-linked-list

是的,这是作业。我必须撤销单一链接列表。导师/朋友告诉我,我应该使用一个堆栈,所以第一个是最后一个。我有这个并不多,我不知道现在该做什么。 GameEntry列表已经提供。 任何推动正确的方向?

    package project;

import java.util.LinkedList;
import dsaj.arrays.GameEntry;
import net.datastructures.*;

public class reverse {

public static void main(String[] args) 
{SinglyLinkedList<GameEntry>list = new SinglyLinkedList<GameEntry>();


list.addFirst(new GameEntry ("A", 0 ));
list.addFirst(new GameEntry ("B", 1 ));
list.addFirst(new GameEntry ("C", 2 ));
list.addFirst(new GameEntry ("D", 3 ));
list.addFirst(new GameEntry ("E", 4 ));
list.addFirst(new GameEntry ("F", 5 ));
list.addFirst(new GameEntry ("G", 6 ));
list.addFirst(new GameEntry ("H", 7 ));
list.addFirst(new GameEntry ("I", 8 ));
list.addFirst(new GameEntry ("J", 9 ));
System.out.printf("\nList before reverse\n %s", list);

SinglyLinkedList<GameEntry>list2 = new SinglyLinkedList<GameEntry>();
LinkedStack<GameEntry>stack =new LinkedStack<GameEntry>();                 
} 
  }

2 个答案:

答案 0 :(得分:1)

迭代list,将值(在您迭代时)推送到stack。然后将值(从stack)弹出到list2,直到您从stack中删除项目。它可能看起来像

for (GameEntry ge : list) {
    stack.push(ge);
}
while (!stack.isEmpty()) {
    list2.add(stack.pop());
}

答案 1 :(得分:0)

这两种方法应该足够你们两个必须在SLL类

code here

     /**
     * Adds an element to the end of the list.
     * @param e  the new element to add
     */
    public void addLast(E e) {   // adds element e to the end 
      Node<E> newest = new Node<>(e, null);   
      if (isEmpty())
        head = newest;         // special case: previously empty list
      else
        tail.setNext(newest);        // new node after   existing tail
      tail = newest;                    // new node becomes the tail
      size++;
    }

    /**
     * Removes and returns the first element of the list.
     * @return the removed element (or null if empty)
     */
    public E removeFirst() {                   // removes and returns the first element
      if (isEmpty()) return null;              // nothing to remove
      E answer = head.getElement();
      head = head.getNext();                   // will become null if list had only one node
      size--;
      if (size == 0)
        tail = null;                           // special case as list is now empty
      return answer;
    }