I have to shift all of the tokens left by one position in a Linked List.
Here's my code for the method:
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);
}
*/
A nullpointer error appears during runtime when I call the method. Any help would be appreciated. Thanks.
You have to think about some points:
1) If your link list does not contain any element then what?
2) For all tokens to be shifted you have to use while-loop.
I assume that head
and tail
are properly updated on insert
and remove
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;
}
UPDATE:
From the comment I see that the OP mentions about a circular list. This is not mentioned in the OP or apparent from the code. I will leave the answer as is.
If it is circular linked list and your add method works properly.
public void shiftLeft(){
head = head.next; tail = tail.next;
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.