Thursday, 9 July 2015

Link Lists Basics

So I finished the section on link lists.

This post will be on the basics of link lists and how to manipulate them.

So my code on github was very inefficient. But I updated the efficient code within comments so no worries.

What they taught us in school was using malloc and how to create link lists based on that.

Due to all the memory manipulation, I honestly liked the concept of link lists, but I hated on its implementation. So I took some time reading online for its manipulation.


It was actually pretty easy.

struct node
{
node *next;
int x;
};

So you have a pointer node and a value x for each node you create and don't forget the semi colon after the struct.

Here's where it made a big difference for me.

Apparently you can create a new node without its explicit memory allocation using malloc by simply using

node *cond;
cond=new node;


That's it. (This goes to show you, that the things you learn in school may not be the most straight forward);

Manipulation with link lists are using 2 pointers namely a slowrunner and a fastrunner.

Slowrunners tend to traverse the list slower than fastrunners which make them useful in several algorithms. (I'll explain them as I go into the problems).

Personally, I always keep a pointer at the start of the link list and never modify it. It makes it simple to access the beginning of the link list.

If you want to delete a node

node1->next=node2->next;

By assigning the next of node1 to the next of node2(meaning node 3), you've actually removed the node2 from the linklist.

That's basically it. Nothing to fancy. Now to the questions.

No comments:

Post a Comment