Java Language
Add a method (convertToRing ()) that converts the list to a circular. This is, which makes the last node instead of pointing to null point to the first.
Code:
class Node {
int value;
Node nextNode;
Node(int v, Node n)
{
value = v;
nextNode = n;
}
Node (int v)
{
this(v,null);
}
}
class LinkedList
{
Node head; //head = null;
LinkedList()
{
}
int length()
{
Node tempPtr;
int result = 0;
tempPtr = head;
while (tempPtr != null)
{
tempPtr = tempPtr.nextNode;
result = result + 1;
}
return(result);
}
void insertAt(int v, int position)
{
Node newNode = new Node(v,null);
Node tempPtr;
int tempPosition = 0;
if((head == null) || (position ==0))
{
newNode.nextNode = head;
head = newNode;
}
else {
tempPtr = head;
while((tempPtr.nextNode != null)&&(tempPosition < position -1))
{
tempPtr = tempPtr.nextNode;
tempPosition = tempPosition + 1;
}
if (tempPosition == (position - 1))
{
newNode.nextNode = tempPtr.nextNode;
tempPtr.nextNode = newNode;
}
}
}
public String toString()
{
Node tempPtr;
tempPtr = head;
String result = "";
while(tempPtr != null)
{
result = result + "[" + tempPtr.value + "| ]-->";
tempPtr = tempPtr.nextNode;
}
result = result + "null";
return result;
}
}
public class LinkedListDemoInsDel
{
public static void main(String[] args)
{
LinkedList aLinkedList = new LinkedList();
aLinkedList.insertAt(1,0);
aLinkedList.insertAt(9,1);
aLinkedList.insertAt(13,2);
aLinkedList.insertAt(8,1);
aLinkedList.insertAt(3,2);
System.out.println(aLinkedList);
System.out.println("Largo de lista: " + aLinkedList.length());
}
}
static Node convertToRing(Node head)
{
// declare a node variable
// start and assign head
// node into start node.
Node start = head;
// check that while head.next
// not equal to null then head
// points to next node.
while (head.next != null)
head = head.next;
// if head.next points to null
// then start assign to the
// head.next node.
head.next = start;
return start;
}
Get Answers For Free
Most questions answered within 1 hours.