You are on page 1of 14

CS-250

DATA STRUCTURES &


ALGORITHMS
MEHREEN TAHIR
Lists

LECTURE-4
LIST
• List is the simplest linked structure.
• The three basic operations supported by lists
are searching, insertion, and deletion
LINKED LIST DATA STRUCTURE
• Overcomes the limitations of array based
organization
• A linked list is a dynamic data structure that
grows and shrinks without any limitation on
size (except memory space, of course)
(LINEAR) LINKED LIST

info next info next info next

first NULL

node node node


LINKED LIST IMPLEMENTATION
// representing a node
NODE
struct node info next
{
int info; 5 POINTER

node * next;
};
LINKED LIST IMPLEMENTATION
struct list
{
node * first;
void initialize () // initialize list
{first=NULL;
}

bool empty() //check empty list


{if (first==NULL)
return true;
else
return false;
}
LINKED LIST IMPLEMENTATION
void traverse() //traverse
{ if (empty()==false){
node * p=first;
while (p!=NULL)
{cout<<p->info<<endl;
p=p->next;} }
else
{ cout<<"list is empty"<<endl; }
}
LINKED LIST IMPLEMENTATION
void InsertAtEnd(int val) //insert a node at end of linked list
{
if (empty()==true)
{node *n=new node;
first=n;
n->info=val;
n->next=NULL;}
else{
node *p=first;
while(p->next!=NULL)
{p=p->next;}
node *n=new node;
p->next=n;
n->info=val;
n->next=NULL;}}
LINKED LIST IMPLEMENTATION
void RemoveFromEnd() //remove a node from end of linked list
{
if (empty()==true)
{cout<<"nothing to remove"<<endl;
exit(1);}
node * p ; node * s ;
p= first;
while(p->next!=NULL)
{s=p;
p=p->next;}
s->next=NULL;
delete p;
p=NULL;
}
LINKED LIST IMPLEMENTATION
void SearchElement (int val) // search element in linked list
{
if (empty()==true)
{
cout<<"nothing to remove"<<endl;
exit(1); }
node * p = first;
while(p->info!=val && p->next !=NULL)
{p=p->next;}
cout<<p->info<<endl;
}
};
LINKED LIST IMPLEMENTATION
void main()
{
list l;
l.initialize();
if (l.empty()==true)
cout<< "list is empty"<<endl;
l.InsertAtEnd(10);
l.InsertAtEnd(20);
l.InsertAtEnd(30);
l.traverse();
l.SearchElement(20);
l.RemoveFromEnd();
l.traverse();
}
ARRAYS VS LINKED LISTS
• Linked structures
– require extra space for storing pointer fields.
– do not allow efficient random access to items.
– Overflow can never occur unless the memory is
actually full.
– Insertions and deletions are simpler than for
contiguous (array) lists.
– With large records, moving pointers is easier and
faster than moving the items themselves.
ARRAYS VS LINKED LISTS
• Arrays allow better memory locality and cache
performance than random pointer jumping.

You might also like