0% found this document useful (0 votes)
5 views5 pages

Insert Node in Sorted Linked List

The document outlines a Java program designed to insert a node into a sorted linked list. It includes an algorithm detailing the steps for node insertion and provides the complete code implementation for the linked list and node classes. The program allows user input for node values and displays the resulting linked list after insertions.

Uploaded by

Gaurav Kumar
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views5 pages

Insert Node in Sorted Linked List

The document outlines a Java program designed to insert a node into a sorted linked list. It includes an algorithm detailing the steps for node insertion and provides the complete code implementation for the linked list and node classes. The program allows user input for node values and displays the resulting linked list after insertions.

Uploaded by

Gaurav Kumar
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOC, PDF, TXT or read online on Scribd

PROGRAM 11:

AIM:
To write the java program to insert a node in a sorted linked list.
ALGORITHM:
1. Start the program.
2. Import the header file.
import [Link].*;
3. Declare the class, object and main function.
class node
4. Declare the variables.
int data;
5. Ptr=start
6. NEWPTR=new Node
7. if NEWPTR=NULL
8. else
9. [Link]=ITEM
[Link]=NULL
[Link] START=NULL then
[Link]=NEWPTR
[Link] if ITEM<[Link] then
[Link]=start
[Link]=NEWPTR
[Link]=Save
[Link]=Start
[Link] steps 16 through 22 until ptr=NULL
[Link] [Link]<[Link] then
[Link]=ptr
[Link]=[Link]
[Link]
[Link]=NEWPTR
[Link]=ptr
[Link]
[Link] ptr=NULL then
[Link]=NEWPTR
[Link]=NULL
[Link]=NULL
[Link] the program.
COADING:

import [Link].*;
class Node
{
protected int data;
protected Node link;
public Node()
{
link=null;
data=0;
}
public Node(int d,Node n)
{
data=d;
link=n;
}
public void setlink(Node n)
{
link=n;
}
public void setData(int d)
{
data=d;
}
public Node getlink()
{
return link;
}
public int getData()
{
return data;
}
}
class linkedList
{
protected Node start;
public linkedList()
{
start=null;
}
public boolean isEmpty()
{
return start==null;
}
public void Insert(int val)
{
Node nptr,ptr,save=null;
nptr=new Node(val,null);
Boolean ins=false;
if(start==null)
{
start=nptr;
}
else if
{
(val<=[Link]());
[Link](start);
start=nptr;
}
else
{
save=start;
ptr=[Link]();
while(ptr!=null)
{
if(val>=[Link]()&&val<=[Link]())
{
[Link](nptr);
[Link](ptr);
ins=true;
break;
}
else
{
save=ptr;
ptr=[Link]();
}
}
if(ins==false)
{
[Link](nptr);
}
}
}
public void display()
{
Node ptr=start;
[Link]([Link]()+"-->");
ptr=[Link]();
while([Link]()!=null)
{
[Link]([Link]()="-->");
ptr=[Link]();
}
[Link]([Link]()+"!!!!");
[Link]();
}
}
class linListTest
{
protected static linkedList S;
public static void main(String[]args)
{
int num;
S=new linkedList();
BufferedReaderbr=new BufferedReader(new
InputStreamReader([Link]));
[Link]("……Starting List Test for INSERTION……\n");
for(int a=0;a<5;++a)
{
[Link]("Enter a number :");
try
{
num=[Link]([Link]());
[Link](num);
[Link]("Inserted : "+num);
}
catch(Exception e)
{
[Link](e);
}
}
[Link]("\n created List is :");
[Link]();
[Link]("\n---List test over---");
}
}

Common questions

Powered by AI

The program uses two constructors within the Node class. The default constructor initializes the 'link' field to null and 'data' to zero, while the parameterized constructor allows specifying initial values for 'data' and 'link'. This flexibility is beneficial because it enables the creation of nodes that are either in a default unlinked state or purposefully initialized to be immediately integrated into a list, thereby enhancing modularity and control over object creation .

The Java program uses the 'Insert' method to add a node into a sorted linked list. It ensures that the list remains sorted by traversing the list starting from the head. It first checks if the list is empty or if the new node's value is less than or equal to the current head, in which case the new node is inserted before the head. If not, it continues to traverse the list until it finds a node with a greater value, inserting the new node before that node by adjusting the pointers appropriately .

If a new node's value is greater than all existing nodes in the list, the program has a specified condition at the end of the 'Insert' method that will execute if 'ins' (a flag for insertion) is false after the loop. This condition uses 'save.setlink(nptr)' to link the last node's 'save' pointer to the new node, effectively appending the new node at the end of the list .

The program uses two pointers, 'save' and 'ptr', to facilitate insertion into the linked list. 'Save' keeps track of the node before the insertion point, and 'ptr' is used to traverse the list. By adjusting these pointers, where 'save.setlink(nptr)' and 'nptr.setlink(ptr)', the program inserts the new node correctly without losing any part of the list. This approach ensures that the new node is properly linked into the existing structure without disrupting the order of the nodes .

When inserting a node into an empty linked list, the program checks if 'start' is null, indicating that the list is empty. It then assigns the new node to the 'start', effectively making it the head of the list with no additional manipulation needed .

If the Insert method did not check whether the value is less than or equal to 'start.getData()', the program could fail to insert nodes correctly at the head of the list. Nodes with the smallest values might be incorrectly placed elsewhere in the list, therefore disrupting the sorted order. This would lead to a misaligned data sequence where the invariant of sorted order is violated, potentially causing difficulties in any subsequent operations expecting sorted data .

The 'display' method is designed to iterate through the linked list starting from the head, printing each node's data followed by an arrow ('-->') to visually indicate the link between nodes. The method uses a 'ptr' pointer to traverse the list and prints each node's value until 'ptr.getlink()' is null, indicating it has reached the last node. It then prints the last node followed by exclamation marks ('!!!!') to indicate the end of the list .

The program uses a 'try-catch' block to manage incorrect input data during list insertion tests. It attempts to parse the input using 'Integer.parseInt', and if any exception occurs during parsing, such as non-numeric input, the catch block captures it and prints the exception to the console, thus preventing the program from crashing and providing feedback about the input error .

Encapsulation in the node class is demonstrated through the use of protected members and public methods. The class encapsulates its data with the 'data' and 'link' fields marked as protected, meaning they are not directly accessible outside the class and its subclasses. Instead, public methods like 'getLink', 'getData', 'setLink', and 'setData' provide controlled access to these fields, allowing for operations on the data while preserving the integrity and security of the inner class state .

The 'ins' flag is used to indicate whether the new node has been inserted in the middle of the list. During traversal, if the new node fits between two existing nodes, 'ins' is set to true, and the loop breaks. This prevents unwanted further iterations and allows the program to immediately add the new node. If 'ins' were removed, the loop might continue unnecessarily, increasing computational costs and potentially compromising the insertion logic .

You might also like