Linked List :
It is a DataStructure. It means the way of organising the data in side the memory is called datastructure. The bellow code is used for traversing all the nodes.
1
2
3
4
5
6
7
8 | /*Display all the nodes from talking the head node*/
public void printAllLinkedList(Node headNode) {
while(headNode.nextNode !=null) {
System.err.print(headNode.data+"-->");
headNode = headNode.nextNode;
}
System.err.print(headNode.data);
}
|
The Below code is used for adding a node at last.
1
2
3
4
5
6
7
8
9
10 | /*
* Inserting node at last by talking headnode for traversing , lastnode for adding node at last
*/
public void insertNodeAtLast(Node headNode,Node lastNode) {
Node currentNode = headNode;
while (currentNode.nextNode != null) {
currentNode = currentNode.nextNode;
}
currentNode.nextNode=lastNode;
}
|
The Below code is used for get the number of nodes by talking the 1st node
1
2
3
4
5
6
7
8
9
10
11 | /*
* return the no of nodes present in the linked list.
*/
public int linkedListCount(Node headNode) {
int count=1;
while (headNode.nextNode != null) {
count++;
headNode = headNode.nextNode;
}
return count;
}
|
The Below code is used for inserting the node at starting point
1
2
3
4
5
6 | /*
* Code is used for inserting the node at starting point
*/
public void insertNodeAtFirst(Node headNode,Node newNode) {
newNode.nextNode = headNode;
}
|
The Below code is used for inserting the node at desired index position
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28 | /*
* Code is used for inserting the node at desired index position
*/
public void insertNodeAtDefinedPosition(Node headNode,int position,Node newNode) {
int indexPos =1;
int count =linkedListCount(headNode);
while (headNode.nextNode !=null)
{
if(position == count) {
insertNodeAtLast(headNode, newNode);
break;
}else if(position == 0) {
insertNodeAtFirst(headNode,newNode);
break;
}else
{
if(indexPos == position) {
Node tempNode = headNode.nextNode;
headNode.nextNode = newNode;
newNode.nextNode = tempNode;
break;
}else {
indexPos++;
}
}
headNode = headNode.nextNode;
}
}
|
Comments
Post a Comment