queue using linked list code example
Example 1: queue with linked list in c
#include<stdio.h>
#include<stdlib.h>
struct node
{
int data;
struct node *next;
};
struct node *front = NULL, *rear = NULL;
void enqueue(int val)
{
struct node *newNode = malloc(sizeof(struct node));
newNode->data = val;
newNode->next = NULL;
if(front == NULL && rear == NULL)
front = rear = newNode;
else
{
rear->next = newNode;
rear = newNode;
}
}
void dequeue()
{
struct node *temp;
if(front == NULL)
printf("Queue is Empty. Unable to perform dequeue\n");
else
{
temp = front;
front = front->next;
if(front == NULL)
rear = NULL;
free(temp);
}
}
void printList()
{
struct node *temp = front;
while(temp)
{
printf("%d->",temp->data);
temp = temp->next;
}
printf("NULL\n");
}
int main()
{
enqueue(10);
enqueue(20);
enqueue(30);
printf("Queue :");
printList();
dequeue();
printf("After dequeue the new Queue :");
printList();
dequeue();
printf("After dequeue the new Queue :");
printList();
return 0;
}
Example 2: Linked List implementation
public class LinkedList {
private Node head;
private int length = 0;
public LinkedList() {
this.head = new Node(null);
}
public int size() {
return length;
}
public void add(Object data) {
Node node = new Node(data);
Node iterator = head;
while (iterator.getNext() != null){
iterator = iterator.getNext();
}
iterator.setNext(node);
length++;
}
public Object get(int index) {
if (head.getNext() == null || index >= length){
return null;
}
Node iterator = head.getNext();
int counter = 0;
while(counter < index){
iterator = iterator.getNext();
counter++;
}
return iterator.getData();
}
public int indexOf(Object data) {
Node obj=head;
for (int i = 0; i < length; i++) {
obj = obj.getNext();
if (obj.getData().equals(data)) {
return i;
}
}
return -1;
}
public boolean remove(Object data) {
if (head.getNext() == null){
return false;
}
Node iterator = head;
while(iterator.getNext() != null){
if (iterator.getNext().getData().equals(data)){
iterator.setNext(iterator.getNext().getNext());
length--;
return true;
}
iterator = iterator.getNext();
}
return false;
}
private class Node {
private Object data;
private Node next;
public Node(Object data) {
this.data = data;
next = null;
}
public Object getData() {
return data;
}
public void setData(Object data) {
this.data = data;
}
public Node getNext() {
return next;
}
public void setNext(Node next) {
this.next = next;
}
}
}