Linked list is somewhat similar to struct of array, it's used to store some data that are somewhat related. Example is storing data of name and age using either linked list or array are possible. But there are also differences between those two. Array are stored in a fixed memory while you can always add more memory space when you're using linked list. The down side of using linked list is the process will take slower time and it is a lot more difficult to do instead of using just arrays. You will understand why later on in this discussion.
Linked list is a collection of similar data in which is connected by pointers. There are 3 types of linked list.
The differences between them are, singly can only point towards the next set of data and could end as it reaches the tail. Doubly have pointer that points towards the previous data in which they could go back and forth. Multiple as the name tells have multiple pointers and could get really complicated. The rules of using linked lists are, the head and the tail of the list must be after or before NULL.
Code:(Singly linked list)
To start creating a linked list, firstly you need to make a struct.
struct tnode {
int value;
char name[100];
}*head=NULL; //declare that the head is pointing towards NULL
To add data you need determine where you want to put your data. Either in the front, back or the middle. In order to simplify it, you need to make a function. But what you really need to remember is you're trying to move a set of data. So what you need is a function that could move a set of memory and allocate them into the preferred location, in other words you need malloc.
struct tnode *node = (struct tnode*) malloc(sizeof(struct tnode));
Then afterwards decide where to put the data.
Head:
node=>value = x; //Input. '=>' means to point and exchange the '.' when we use normal struct
node=>strcpy(name , y);
node=>strcpy(name , y);
node=>next = head; //next = head means to point towards the head
head = node; //node becomes head
Middle
/*add data first*/
curr = head -> next
temp (struct tnode *temp)
temp -> next = curr -> next
curr-> next = temp
Middle
/*add data first*/
curr = head -> next
temp (struct tnode *temp)
temp -> next = curr -> next
curr-> next = temp
End
node=>prev = tail;
tail = node;
tail = node;
Code:(Doubly Linked List)
Its the same as singly linked list but don't forget that the data needs to point to the next set and the previous set.
That is all for this session. In the next post I will discuss further regarding linked list. Until next time.
No comments:
Post a Comment