Upload
anandduraiswamy
View
215
Download
0
Embed Size (px)
DESCRIPTION
LI
Citation preview
A Singly Linked List
What is a singly linked list? A linked list is a series of nodes in memory such that:
1. There is a starting node.
2. Each node contains a pointer that points to the next or child node.
3. If a node does not have a child node then its pointer is set to NULL.
4. Each node contains data, maybe a lot of it.
5. The linked list also has functions that manage the list by performing additions,
deletions, changing the data of a node, returning the number of nodes, etc., etc.
What is a linked list used for? A linked list is used for the same purposes as an array. However, the linked list has some
advantages:
An array is of fixed size (unless it is dynamically allocated), a linked list can grow by
grabbing new memory off the heap as needed.
If you store a list in an array and then delete an item in the middle, then you must move a lot
of items down one to close up the gap. But in a linked list, you simply reroute the pointers
around the node to delete, and then you delete it.
A singly linked list class The class definition for a node #include
#include
using namespace std;
typedef string listType;
class node
{
public:
node (listType);
voidsetData (listType);
voidsetNext (node*);
listTypegetData () const;
node* getNext () const;
private:
listType data;
node* next;
};
The functions for the node class #include "node.h"
node::node (listType it)
{
//pre-condition: it is the datum to be stored in the node
//post-condition: it gets stored in the node
data = it;
next = NULL;
}
void node::setData (listType it)
{
data = it;
}
void node::setNext (node* aNode)
{
next = aNode;
}
listType node::getData () const
{
return data;
}
node* node::getNext () const
{
return next;
}
The class definition for the linked list #include "node.h"
class linked
{
public:
linked ();
linked (linked&);
linked (listType [], int);
~linked ();
intgetSize ();
voidaddOnEnd (listType);
voidinsertBefore (int, listType);
voiddeleteLink (int);
voidsetDataInLink (int, listType);
listTypegetNthData (int);
private:
node* head;
node* tail;
int size;
voiddeleteAll ();
node* getNthAddress (int);
voiddeleteWithOneNode ();
voiddeleteAtBeginning ();
voiddeleteLast ();
voiddeleteInMiddle (int);
};