递归链表

时间:2014-03-09 19:47:49

标签: java recursion linked-list

我有一个小问题。我无法实现递归   - addlast   - 去除   - 尺寸   - 打印   - PrintReverse 在链表中。 这基本上就是我现在所需要的。在此先感谢BTW 它一直告诉我要添加更多描述,所以我必须添加一些随机文本。所以我想你可以忽略这一点。

package oop.recursive.linkedlist;

public class LinkedList<T> implements IList<T>
{
  private Node<T> head = null;

  private class Node<T>
  {
    T elem;
    Node<T> next;

    public Node (T elem, Node<T> next)
    {
      this.elem = elem;
      this.next = next;
    }
  }

  @Override
  public void addFirst (T element)
  {
    head = new Node<T>(element, head);
  }

  @Override
  public void addLast (T element)
  {
    head = recAddLast (head, element);
  }

  @Override
  public T removeFirst ()
  {
    // TODO Auto-generated method stub
    return null;
  }

  @Override
  public T removeLast ()
  {
    return recRemoveLast (head);
  }

  @Override
  public int size ()
  {
    return recSize (head);
  }

  @Override
  public void print ()
  {
    recPrint (head);
  }

  @Override
  public void printReverse ()
  {
    recPrintReverse (head);
  }

  // recursive help methods:

  private Node<T> recAddLast (Node<T> list, T element)
  {
    return null;
  }

  private T recRemoveLast (Node<T> list)
  {
    return null;
  }

  private int recSize (Node<T> list)
  {
    return -1;
  }

  private void recPrint (Node<T> list)
  {

  }

  private void recPrintReverse (Node<T> list)
  {

  }
}

1 个答案:

答案 0 :(得分:1)

定义另外2个私有变量

private Node<T> tail = null;
private int size = 0;

@Override
  public void addFirst(T element)
  {
    head = new Node<T>(element, head);
    if(head.next = null)
        tail = head;
    size++;
  }



 @Override
  public void addLast (T element)
  {
    if(tail == null)
        addFirst(element);
    else{
        tail.next = new Node<T>(element, null);
        tail = tail.next;
    }
    size++;
  }

 @Override
  public T removeFirst ()
  {
    if(head != null)
    {
       T val = head.elem
       head = head.next;
       //First element will be clear by garbage collector, since it has no reference
       size--;
       return val;
    }
    else
        return null;
  }

@Override
  public T removeLast ()
  {
      T val = null;
      if(size > 1)
      {
         val = tail.elem;
         Node<T> itr = head;
         for(int i=0; i<size-2; i++)
           itr = itr.next;
         tail = itr;
         itr.next = null;//last element will be removed by garbage collector
         size--;
      }
      else if(size == 1)
      {
         val = head.elem;
         head = null;
         tail = null;
         size--;
      }
      return val;
  }
  @Override
  public int size ()
  {
    return size;
  }

如果您不想使用尾巴,可以避免使用它。 但是你必须循环到最后一个元素addLast。