public class LinkedListClass {
private Node first;
private Node last;
/*** Private class similar to a linked list node contains a data field and a pointer to next node in list***/
private class Node
{
int data;
Node next;
}
/**
* Checks if a list if empty or not
* @return
*/
public boolean isEmpty()
{
return first == null;
}
/*** Traverse Entire linked list and print data items one by one ***/
public void traverse()
{
for(Node track = first; track!=null; track=track.next)
{
System.out.println(track.data);
}
}
/**
* Insert Data item in front of linked list
* @param data
*/
/***** Insert Functions ****/
public void insertAtFront(int data)
{
Node oldNode = first;
first = new Node();
first.data = data;
first.next = oldNode;
}
/**
* Insert Data item at end of linked list
* @param data
*/
public void insertAtEnd(int data)
{
Node oldLastNode = last;
last = new Node();
last.data = data;
last.next = null;
if(isEmpty())
first = last;
else
oldLastNode.next = last;
}
/**
* Insert Data item in linked list at specified position
* @param data
* @param pos
*/
public void insertAtPos(int data,int pos)
{
// Maintain a count varibale
int count = 0;
// Traverse through the list
for(Node track = first; track!=null; track=track.next)
{
count++;
// Maintain two pointers for keep track of previous and forward node
Node prev = track;
Node forward = track.next;
// If pos-1 is equal to count
if(pos-1 == count)
{
// Make a new Node
Node newNode = new Node();
// Insert Data into new Node
newNode.data = data;
// Set newNode next pointer to forward node
newNode.next = forward;
// set previous node's next pointer to point to newNode
prev.next = newNode;
}
}
}
/****** Delete Functions *****/
/**
* Delete node from front of linked list
*/
public void deleteAtFirst()
{
// Move first pointer to next node rest work is done by java Garbage Collector
first = first.next;
}
/**
* Delete node from end of the linked list
*/
public void deleteAtLast()
{
// Traverse All Linked List
for(Node track = first; track!=null; track=track.next)
{
// Maintain two pointer previous and forward
Node prev = track;
Node forward = track.next;
// if we reach at end of list
if(forward.next == null)
{
//Then set previous node's next part to null
prev.next = null;
}
}
}
/**
* Delete node at specified position
* @param pos
*/
public void deleteAtPos(int pos)
{
//Maintain a count variable
int count = 0;
// Traverse through the list
for(Node track = first; track!=null; track=track.next)
{
count++;
// Maintain two pointer previous and forward keeps track of nodes
Node prev = track;
Node forward = track.next;
// If pos-1 is equal to count
if(pos-1 == count)
{
//Bypass node that we have to delete by setting previous node's next pointer to forward node(that is next to the node that we have to delete)
// Rest is done by java's automatic garbage collector
prev.next = forward.next;
}
}
}
单链表的算法实现
最新推荐文章于 2024-09-25 11:06:23 发布