繁体   English   中英

通过链接堆栈反向单链接列表

[英]Reverse a Singly linked list through Linked Stack

是的,这是做作业。 我必须扭转一个单链表。 老师/朋友告诉我,我应该使用堆栈,因此第一个进入的是最后一个。 我所拥有的这根本不多,我也不知道现在该怎么办。 已经提供了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>();                 
} 
  }

迭代list ,将值(迭代时)推入stack 然后将值(来自stack )弹出到list2直到没有stack的项目为止。 它可能看起来像

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

这两个方法对您都必须在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;
    }

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM