Hi,
I have been trying to re-create the infamous singly linked list code, implemented using C, with the help of core
java.
I am trying to incorporate the functionality, like
1. create a node
2. insert a node,
2.1. at the beginning of the list
2.2. at the end of the list
2.3. in between the list
3. remove
4. modify
5. print the list
and sadly am stuck at inserting in-between the list.
what i am trying to do is to take data and link as int, if i want to insert in between then find the node whose link is same as that of the incoming node and increment the link of the nodes with link value greater than the incoming link.
and yes there is headCount to keep track of the number of elements
whew!!!
here is the piece of code i have created,
--------------------------------------------------------------------------
class Node.java
public class Node {
public Node head, nextNode;
public Node newNode;
public int data, link;
public static int headCount=0;
public Node(int data, int link){
this.link=link;
this.data=data;
}
public void setLink(int link){
this.link= link;
}
public void printList(){
System.out.println("{"+data+","+link+"}");
}
}
class Operations.java
public class Operations {
public Node firstNode, lastNode;
public Node currentNode;
public Operations(){
firstNode=null;
// nextNode=null;
currentNode=null;
lastNode=null;
}
public void insert(int data, int link){
// entry values are 0, -ve or greater than the accepted value
if(link<=0 || link>Node.headCount+1){
System.out.println("invalid entry, cannot be 0, -ve or greater than "+(Node.headCount+1));
}
if(link>0){
// element entering at location 1
if(link==1){
//first element
if(Node.headCount==0){
Node newNode= new Node(data, link);
firstNode=newNode;
lastNode=newNode;
newNode.nextNode=null;
lastNode.nextNode=null;
Node.headCount++;
System.out.println("{"+newNode.data+","+newNode.li nk+"}");
}
// Beginning of the list
if(Node.headCount==1){
Node newNode= new Node(data, link);
firstNode.link=(firstNode.link+1);
currentNode=firstNode;
lastNode=currentNode;
newNode.nextNode=lastNode;
newNode=firstNode;
lastNode.nextNode=null;
currentNode=null;
}
Node.headCount++;
}
// at the end of the list
if(link>1 && link==(Node.headCount+1)){
Node newNode= new Node(data, link);
lastNode.nextNode=newNode;
newNode=lastNode;
newNode.nextNode=null;
Node.headCount++;
}
//In-between
if(link>1 && link<(Node.headCount+1)){
Node newNode= new Node(data, link);
currentNode.link= newNode.link;
//temp.nextNode=currentNode;
while(currentNode.nextNode != null){
currentNode.link=(currentNode.link+1);
currentNode=currentNode.nextNode;
}
}
}
}
// the print functionality is incomplete, but i am posting it anyway
public void printList(){
Node curr= firstNode;
while(curr != null){
curr.printList();
curr=curr.nextNode;
}
}
}
class Test.java
public class
Test {
public static void main(
String[] args) {
Operations operate= new Operations();
operate.insert(10, 1);
operate.insert(20, 1);
}
}