Monday, March 24, 2014

Lesson 2: Linked List Implementation

After learning about Singly Linked List, now let's see what are their implications.

As you all know from the previous lesson, single linked list only have a tail that points towards the next data. Now for example you want to make a MP3 player that could play all the songs and repeat it again as soon as it finishes its last song. Some of you may think that using a single linked list isn't possible here. But there is a trick to it in order for you to recall the first data from the last data. And to do that, we are going to make a special single linked list called the Circular Linked List!


Circular Singly Linked List


Code:

Firstly you need to make the place to store the data which as we all know as struct.

struct Playlist(){
char name[50];
int duration;
struct Playlist *next;
}*head=NULL; *tail=NULL;

Then we make the functions for adding data.

void pushFront(char name[], int duration){

struct Playlist *temp=(struct Playlist*) malloc(sizeof(struct Playlist));
strcpy(temp->name, name);
temp->duration=duration;

if(!head){
head=tail=temp;
head->next=NULL;
}else{
temp->next=head;
temp=head;
}
tail->next=head;
}


Then after we make the function for adding, we just need to make a function to play. Here is the tricky part. We first need to know how much songs we have added to the playlist so then it could be played automatically. To do that we need to use a function I like to call int check.

int check(){
Playlist *curr;
curr=head;
int a=0;
while(curr!=NULL){
curr=curr->next;
a++
}
return a;
}

void play(){
Playlist *curr;
curr=head;
int a=check();
for(int i=1; i<=a; i++)
     printf("|%-25s|", curr->name);
     for(int j=0; j<curr->duration;j++){
     printf("|%-5d|%-5d|\n",  j, curr->duration); Sleep(1000);
     }
     system("cls");
     curr=curr->next;
}

This code is just a rough example. I'm still confused in how should I make the timer ticks down while erasing the previous print and also preventing the title of the song from being erased. If any of you know how to do so, you could post it down below in the comments. It will surely help.

Then after that you could make the menu that could show, add, play and finally exit the program.

That is sort of all of the lessons for today. Next lesson I will be discussing about double linked list. Until next time.

No comments:

Post a Comment