Hello everyone. I created a doubly linked list that perform some operations. I can process my target just one character. But, I need to do with multi characters. How can i fix it? Thank you very much!
I added my code file below.
Code:
#include <stdio.h>
#include <stdlib.h>
struct Node {
char address;
int numberOfRequest;
struct Node* next;
struct Node* prev;
};
typedef struct Node Node;
Node* head;
Node* temp;
Node* GetNewNode(int request, char webPage) {
Node* newNode = (Node*)malloc(sizeof(Node));
newNode->numberOfRequest = request;
newNode->address = webPage;
newNode->next = NULL;
newNode->prev = NULL;
return newNode;
}
void InsertAtHead(int request, char webPage) {
Node* newNode = GetNewNode(request, webPage);
if (head == NULL) {
head = newNode;
return;
}
else {
head->prev = newNode;
newNode->next = head;
head = newNode;
}
}
int bufferControl(char pageName) {
temp = head;
int flag;
if (head == NULL) {
flag = 0; // list is empty
}
else {
while (temp != NULL) {
if (temp->address == pageName) {
flag = 1;
break;
}
else {
flag = 0;
}
temp = temp->next;
}
}
return flag;
}
int increaseCounter(char pageName) {
int threshold;
temp = head;
while (temp->address != pageName) {
temp = temp->next;
}
temp->numberOfRequest = (temp->numberOfRequest) + 1;
threshold = temp->numberOfRequest;
return threshold;
}
void performAsHeadNode(char webPageName) {
Node* temp2;
temp = head;
while (temp->address != webPageName) {
temp = temp->next;
}
if (temp->next == NULL) { // if node is last element
temp->prev->next = NULL;
temp->next = head;
temp->prev = NULL;
head->prev = temp;
head = temp;
}
else if(temp->prev==NULL){
temp->next = head->next;
head->next->prev = temp;
head = temp;
}
else {
temp->prev->next = temp->next;
temp->next->prev = temp->prev;
temp->prev = NULL;
temp->next = head;
head->prev = temp;
head = temp;
}
}
int numberOfNode() {
int count = 0;
temp = head;
while (temp != NULL) {
count++;
temp = temp->next;
}
return count;
}
void DeleteAtLast() {
Node* temp = head;
while (temp->next != NULL) {
temp = temp->next;
}
temp->prev->next = NULL;
free(temp);
}
void Print() {
Node* temp = head;
printf("Cache Buffer: ");
while (temp != NULL) {
printf("(%c, %d) ", temp->address, temp->numberOfRequest);
temp = temp->next;
}
printf("\n");
}
int main(int argc, char *argv[]) {
int increment = 0;
int counterNode = 0;
int T_VALUE, L_VALUE;
printf("Enter the T Value:");
scanf("%d", &T_VALUE);
printf("Enter the L Value:");
scanf("%d", &L_VALUE);
char webPageName;
while (scanf(" %c", &webPageName) != 120) {
int bf = bufferControl(webPageName);
if (bf == 0) {
InsertAtHead(1, webPageName);
}
counterNode = numberOfNode(webPageName);
if (counterNode > L_VALUE) {
DeleteAtLast();
}
else if (bf == 1) {
increment = increaseCounter(webPageName);
//Print();
if (increment > T_VALUE) {
performAsHeadNode(webPageName);
//Print();
}
}
Print();
}
return 0;
}