♠ Posted by Unknown in Artificial Intelligent,Data Structure at 01:42
Sequential Linked List
/*Author: Viral Vyas
* Sequential Linked List
*/
public class SeqListNode {
private int iData;
SeqListNode next;
public SeqListNode()
{ iData = 0; next = null; }
public SeqListNode(int i)
{ iData = i; next = null; }
public int printNode()
{ return iData; }
}
public class SeqListMethods {
SeqListNode root;
public SeqListMethods()
{ root = null; }
public boolean isEmpty()
{
if(root == null)
return true;
else
return false;
}
//Insert new Node at FIRST
public void insertFirst(int i)
{
SeqListNode newNode = new SeqListNode(i);
newNode.next = root;
root = newNode;
}
//Insert new node at LAST
public void insertNode(int i)
{
SeqListNode newNode = new SeqListNode(i);
if(isEmpty())
{
root = newNode;
}
else
{
SeqListNode current = new SeqListNode();
current = root;
while(current.next != null)
current = current.next;
current.next = newNode;
current = newNode;
}
}
//Delete First Node
public SeqListNode deleteFirst()
{
SeqListNode temp = root;
root = root.next;
return(temp);
}
//Delete Selected Node
public SeqListNode deleteSelected(int i)
{
SeqListNode current = root;
SeqListNode previous = root;
while(current.printNode() != i)
{
if(current.next == null)
{
return null;
}
else
{
previous = current;
current = current.next;
}
}
if(current == root)
root = root.next;
else
previous.next = current.next;
return(current);
}
public void displayList()
{
SeqListNode current = new SeqListNode();
current = root;
System.out.print("The List : ");
while(current != null)
{
System.out.print(current.printNode() + " ");
current = current.next;
}
System.out.print("\n");
}
}
public class SeqListMain {
public static void main(String[] args) {
SeqListMethods list = new SeqListMethods();
list.insertNode(10);
list.insertNode(20);
list.insertNode(30);
list.displayList();
//Node is inserted at First Position
list.insertFirst(5);
list.displayList();
//Node: 20 is deleted
list.deleteSelected(20);
list.displayList();
//First Node Deleted
list.deleteFirst();
list.displayList();
}
}
Output:
The List : 10 20 30
The List : 5 10 20 30
The List : 5 10 30
The List : 10 30
0 comments:
Post a Comment