【问题标题】:Shift elements in a linked list in java在java中的链表中移动元素
【发布时间】:2013-04-15 09:14:54
【问题描述】:

我必须将链表中的所有标记左移一个位置。

这是我的方法代码:

private LLNode<E> head;     // the first node in the list
private LLNode<E> tail;     // the last node in the list

public void shiftLeft()
{
    LLNode<E> temp = new LLNode<E>();
    temp = head;
    head = head.next;
    tail.next = temp;
}

/*from main method
TopSpinLinkedList<Integer> ll = new TopSpinLinkedList<Integer>(numTokens, spinSize);

//fills LinkedList with tokens
for(int i = 1; i <= numTokens; i++) {
    ll.add(i);
}
*/

当我调用该方法时,在运行时出现空指针错误。任何帮助,将不胜感激。谢谢。

【问题讨论】:

  • 代码中的 head 是什么?
  • 列表中的第一个节点
  • headtail 必须是 null。如果没有更多的代码(一个完整的可运行程序,用最少的代码重现问题总是有帮助的),我们不可能知道是哪一个。
  • 你有循环linkedList?
  • 你能告诉我们你的完整代码吗?就像你在哪里初始化 head 和 tail。

标签: java linked-list shift doubly-linked-list circular-list


【解决方案1】:

您必须考虑以下几点:
1) 如果您的链接列表不包含任何元素,那该怎么办?
2) 对于要移动的所有标记,您必须使用 while-loop。

【讨论】:

  • 2 不正确。你只需要换个头,我们不是在说数组。
  • 你不需要 while 循环 - 这是我们正在谈论的链表。移动头部就足够了。
【解决方案2】:

我假设 headtailinsertremove 上正确更新

public void shiftLeft()
{
    if(head == null || head.next == null){
       return;    
    }
    LLNode<E> temp = new LLNode<E>();     
    temp = head;           
    head = head.next;  
    temp.next = null;   
    tail.next = temp;  
    tail = temp;  
}  

更新:
从评论中我看到 OP 提到了一个循环列表。这在 OP 中没有提到,也没有从代码中明显看出。我将保持原样。

【讨论】:

  • 尝试此操作后仍会出现空指针异常。这是否意味着我没有正确调整我的 add() 和 remove() 方法?
  • 是的。我怀疑你没有更新tail。你应该在单个元素列表中创建head=tail=node
  • 你能告诉我怎么做 shiftRight() 吗?
  • 这会导致左移:/
【解决方案3】:

如果是循环链表并且你的 add 方法可以正常工作。

public void shiftLeft(){
    head = head.next; tail = tail.next;
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-02-23
    • 2011-12-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多