Learn-dsa..in 30 days!



























CC-16 : Simulate RingBuffer using a CircularSingleLinkedList.

Description:

Write and test code for a Ring buffer of size 5:

As ring buffer is of size 5, maximum 5 data values/ nodes can be stored in it.
Last node of Ring buffer points back to first node.
Ring buffer with 3 items : “11->44->97”. First node is node with data value “11”.
Ring buffer with 5 items “11->44->97->31->66”. First node is node with data value “11”.
Ring buffer when 6th data value “45” is added “44->97->31->66->45”. Node with value “11” has been removed from the Ring buffer.
Ring buffer when 7th data value “57” is added “45->97->31->66->57”. Node with value “44” has been removed from the Ring buffer.

Test cases and expected outputs:

Input Parameters Expected outputs
Add these nodes one by one to RingBuffer and check its contents after each add operation: 1->2->3->4->5->6->7->8 Ring Buffer:1< last node points to first node>
Ring Buffer:1->2 (last node points to first node)
Ring Buffer:1->2->3 (last node points to first node)
Ring Buffer:1->2->3->4 (last node points to first node)
Ring Buffer:1->2->3->4->5 (last node points to first node)
Ring Buffer:2->3->4->5->6 (last node points to first node)
Ring Buffer:3->4->5->6->7 (last node points to first node)
Ring Buffer:4->5->6->7->8 (last node points to first node)

Pseudocode:

Initialize a CircularSingleLinkedList to implement the Ring Buffer.
If CircularSingleLinkedList size is <5, add node to end of CircularSingleLinkedList.
If CircularSingleLinkedList size is =5:
Add node to end of CircularSingleLinkedList.
Remove linkage to original firstNode of CircularSingleLinkedList.
Add linkage to original second node of CircularSingleLinkedList.
Set the second original node as “firstNode” of CircularSingleLinkedList (this means original first node of CircularSingleLinkedList has been removed from the RingBuffer.
Note: Ring Buffer size should never exceed 5 nodes.

Code:

public class CircularSingleLinkedListRingBuffer {
	
CircularSingleLinkedList circularSingleLinkedList=this.new CircularSingleLinkedList();
	
public void circularSingleLinkedListRingBuffer(int addToBuffer) throws Exception{
	int nodeCount=0;
	SingleLinkedListNode currentNode=circularSingleLinkedList.getFirstNode();
	if (currentNode!=null) {nodeCount=1;}
	while ((currentNode !=null) && (currentNode.getNextNode() 
			!= circularSingleLinkedList.getFirstNode()))  {
		nodeCount++;
		currentNode=currentNode.getNextNode();
	}									
	if ((nodeCount>=0)&&(nodeCount<5)) {
		circularSingleLinkedList.addLast(addToBuffer);
	}
	if (nodeCount==5) {
		circularSingleLinkedList.removeFirst();
		circularSingleLinkedList.addLast(addToBuffer);
	}				
}
}

Click here to download and run code and test cases !