added new field and modified some methods

This commit is contained in:
ulvi
2019-01-27 02:26:01 +04:00
parent 6cc1414a2a
commit b123975b56

View File

@ -32,8 +32,16 @@ class SinglyLinkedList{
Node newNode = new Node(x); //Create a new link with a value attached to it Node newNode = new Node(x); //Create a new link with a value attached to it
newNode.next = head; //Set the new link to point to the current head newNode.next = head; //Set the new link to point to the current head
head = newNode; //Now set the new link to be the head head = newNode; //Now set the new link to be the head
Node.indexCount++; //Count the all indexes of inserted values
} }
/**
* Insert values at spesific position
* @param number inserted value
* @param position spesific position of inserted value
*/
public void addToSpecifiedPosition(int number, int position) {
InsertNth(head, number, position);
}
/** /**
* Inserts a new node at a specified position * Inserts a new node at a specified position
@ -45,22 +53,18 @@ class SinglyLinkedList{
Node InsertNth(Node head, int data, int position) { Node InsertNth(Node head, int data, int position) {
Node newNode = new Node(); Node newNode = new Node(data);
newNode.data = data;
if (position == 0) {
newNode.next = head;
return newNode;
}
Node current = head; Node current = head;
int temp = position - Node.getIndexCount();
while (--position > 0) { while (temp-- > 0) {
current = current.next; insertHead(0);
System.out.println("Do something " + Node.indexCount);
} }
newNode.next = current.next; newNode.next = current;
current.next = newNode; head = newNode;
insertHead(newNode.value);
return head; return head;
} }
@ -72,6 +76,7 @@ class SinglyLinkedList{
public Node deleteHead(){ public Node deleteHead(){
Node temp = head; Node temp = head;
head = head.next; //Make the second element in the list the new head, the Java garbage collector will later remove the old head head = head.next; //Make the second element in the list the new head, the Java garbage collector will later remove the old head
--Node.indexCount;
return temp; return temp;
} }
@ -129,6 +134,10 @@ class SinglyLinkedList{
class Node{ class Node{
/** The value of the node */ /** The value of the node */
public int value; public int value;
/**
* The count of Indexes
*/
public static int indexCount;
/** Point to the next node */ /** Point to the next node */
public Node next; //This is what the link will point to public Node next; //This is what the link will point to
@ -147,5 +156,10 @@ class Node{
public int getValue(){ public int getValue(){
return value; return value;
} }
/**
* @return the count of indexes
*/
public static int getIndexCount() {
return indexCount;
}
} }