Professional Documents
Culture Documents
Data Structure
Data Structure
Data Structure
Linked List
ScudComp
Data Structure refers to a data collection with well defined
operations a and behaviour or properties. The term List refers
to a linear collection of data. The List can be of sequential
type or non sequential type.
0 N-1
Start
4 nulll
1200
start Null
8 null
900
Insertion in a sorted List- in between
start
30
a l
30 190 90 4400
10 null s
25
Insertion in a sorted List- in the end
start
30
30 190 90 4400
5 null 78
nptr
Algorithm to insert an element in a singly linked list
Step
1. START
2. ptr =start
3. nptr = new node
4. if start = null then start =nptr
5 else if val <start.data then 5.1
5.1 save =start
5.1 start =nptr
6. else
6.1 save=start
6.2 ptr=starts link
6.3 Repeat steps 6.4 to 6.4.6 until ptr is not equal to null
6.4 if val is greater than saves data and val is less than ptrs data then 6.4.1 else 6.4.5
6.4.1 saves link is nptr
6.4.2 nptrs link is ptr
6.4.3 make ins to be true
6.4.4 break
6.4.5 save should be ptr
6.4.6 ptr = ptr’s link
Node start;
LinkedList()
{
start=null;
}
void insert(int val)
{
Node ptr, save=null;
boolean ins=false;
Node nptr=new Node(val, null);
if(start==null)
start=nptr;
else if(val<=start.getData())
{
nptr.setLink(start);
start=nptr;
}//closure for else if
else
{
save=start;
ptr=start.getLink();
while(ptr!=null)
{
if(val>=save.getData() && val<=ptr.getData())
{
save.setLink(nptr);
nptr.setLink(ptr);
ins=true;
break;
}//closure for if
else
{
save=ptr;
ptr=ptr.getLink();
}
} //closure of while
if(ins==false)
save.setLink(nptr);
}// closure for else
}
Algorithm To Print all the nodes
230 30 1130
2300
Ptr
Delete a node in a list
Algorithm
Step
1. Start
2. save =start, ptr =start boolean res=false
3. If ptr=val then step 4 else 5
4. start=start.link
5. res=true
6. Exiting if construct
if(start.getData()==val)
{ start=start.getLink();
ins=true;
}
else
{
while(ptr!= null)
{
if(ptr.getData()==val)
{
save.setLink(ptr.getLink());
ins=true;
}
else
save=ptr;
ptr=ptr.getLink();
}
}
return ins;
}
public static void main(String args[])
{
LinkedList l =new LinkedList();
int i,no;
for(i=0;i<5;i++)
{
System.out.print("Enter a no");
no=obj.nextInt();
l .insert(no);
}
l.display();
boolean x=l.delete(3);
if(x==true)
System.out.print("deleted");
else
System.out.print("not deleted");
l.display();
System.out.println();
While()
Menu - insert, delete, print , quit
Switch case to branch