java中链表中的Shift元素
我必须将所有标记在链表中移动一个位置 以下是我的方法代码:java中链表中的Shift元素,java,linked-list,shift,doubly-linked-list,circular-list,Java,Linked List,Shift,Doubly Linked List,Circular List,我必须将所有标记在链表中移动一个位置 以下是我的方法代码: 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;
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);
}
*/
private LLNode head;//列表中的第一个节点
私有LLNode tail;//列表中的最后一个节点
公共空间shiftLeft()
{
LLNode temp=新的LLNode();
温度=水头;
head=head.next;
tail.next=温度;
}
/*从主方法
TopSpinLinkedList ll=新的TopSpinLinkedList(numTokens,spinSize);
//用标记填充LinkedList
对于(inti=1;i您必须考虑以下几点:
1) 如果您的链接列表不包含任何元素,那么什么?
2) 对于要移动的所有令牌,您必须使用while循环。
我假设头和尾在插入和删除时正确更新
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;
}
public void shiftLeft()
{
if(head==null | | head.next==null){
返回;
}
LLNode temp=新的LLNode();
温度=水头;
head=head.next;
temp.next=null;
tail.next=温度;
尾=温度;
}
更新:
从评论中我看到OP提到了一个循环列表。OP中没有提到这一点,也没有从代码中明显看出这一点。如果是循环链表,并且您的add方法工作正常,我将保留原样。
public void shiftLeft(){
head = head.next; tail = tail.next;
}
代码中的头是什么?列表中的第一个节点其head
或tail
必须为null
。如果没有更多的代码(一个完整的可运行程序,用最少的代码来重现问题总是有帮助的),我们就不可能知道是哪一个。你有循环链接列表?你能给我们看一下你的完整代码吗?就像你从头到尾一样。2不是真的。你只需要改变头部,我们不是在讨论数组。你不需要while循环-这是我们正在讨论的链表。移动头部应该足够了。尝试此操作后仍会出现nullpointer异常。这是否意味着我没有正确调整add()和remove()方法?是的。我怀疑你没有更新tail
。你应该在一个元素列表中设置head=tail=node
。你是否也可以告诉我如何执行shiftRight()?这会导致左移:/