【问题标题】:Reverse a Singly linked list through Linked Stack通过 Linked Stack 反转单链表
【发布时间】:2015-12-30 05:36:10
【问题描述】:

是的,这是作业。我必须反转一个单链表。导师/朋友告诉我我应该使用堆栈,所以第一个进是最后一个出。我有这个,一点也不多,我不知道现在该做什么。 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>();                 
} 
  }

【问题讨论】:

  • 一个足够成功的应该是堆栈数据结构以与添加(推送)方式相反的顺序删除(弹出)元素......Java中的LinkedList具有行为所需的结构和方法一个堆栈

标签: java stack reverse singly-linked-list


【解决方案1】:

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

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

【讨论】:

    【解决方案2】:

    这两种方法应该足够了,你都必须在 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;
        }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2014-05-24
      • 2016-09-29
      • 1970-01-01
      • 2018-10-16
      • 1970-01-01
      相关资源
      最近更新 更多