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
newNode.next = head; //Set the new link to point to the current 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
@ -45,22 +53,18 @@ class SinglyLinkedList{
Node InsertNth(Node head, int data, int position) {
Node newNode = new Node();
newNode.data = data;
if (position == 0) {
newNode.next = head;
return newNode;
}
Node newNode = new Node(data);
Node current = head;
int temp = position - Node.getIndexCount();
while (--position > 0) {
current = current.next;
while (temp-- > 0) {
insertHead(0);
System.out.println("Do something " + Node.indexCount);
}
newNode.next = current.next;
current.next = newNode;
newNode.next = current;
head = newNode;
insertHead(newNode.value);
return head;
}
@ -72,6 +76,7 @@ class SinglyLinkedList{
public Node deleteHead(){
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
--Node.indexCount;
return temp;
}
@ -129,6 +134,10 @@ class SinglyLinkedList{
class Node{
/** The value of the node */
public int value;
/**
* The count of Indexes
*/
public static int indexCount;
/** Point to the next node */
public Node next; //This is what the link will point to
@ -147,5 +156,10 @@ class Node{
public int getValue(){
return value;
}
/**
* @return the count of indexes
*/
public static int getIndexCount() {
return indexCount;
}
}