First of all :

working with linked lists requires a good knowledge about pointers so if you still finding pointers is a hard topic you can practice out this topic
linked listsLinked lists are type of data structures :

In computer science, a linked list (or more clearly, “singly-linked list”) is a data structure that consists of a sequence of nodes each of which contains a reference (i.e., a link) to the next node in the sequence.

source :wikipedia

so the linked list is a type of datastructure that can stand alone or used to create other data structures it consists of Nodes and each node has the reference to the next node ie : “linked to it ”  until the final node where it doesn’t have anything to point to

you can Create a linked list using Classes or Structures but we are using structure and may it be a good thing just to remember how to deal with structures

here’s a little example about how to initialize a Linked list Item and fill any of it’s data

#include <iostream>
#include <string>
using namespace std ;

 struct  listItem {
 string  name  ;  // name of the item 
listItem * next ;  // pointer points to the next node 
 } ;

void main (){
listItem * head ; // pointer will always points on the first node
listItem * myListItem ;   // creating a new instant from ListItem  
myListItem.name = " Greetings Egyptian Geeks "  ; //filling it's data 
cout << myListItem.name ;
head = &myListItem ;  // making the pointer to the adress of the First Item
}

download from here

simple enough !! , it’s a normal Structure  ,  So let’s Move to the NEW part !

Adding New Item to the beginning of the LinkedList

listItem   myListItem2 ;   // creating a new instant from ListItem 
 myListItem2.name = " add me to the beginnning  "  ; //filling it's data 

 myListItem2.next = head ; // making it point to the Next item -that was first- 

 head = & myListItem2 ;  // making the Head pointer points to the new head one

Adding new element to the End

mylastListItem.Next = &newLastItem ;

Addin new element in the Middle

we have two list items listitem1 and listitem2 we want to put middleListItem in the middle we create a new temp pointer to save the adress of listitem2 in it  – as we can’t access it unless by  listitem1.next

temp = listitem1.next ;
listitem1.next = & middleListItem ;
middlelistItem.next = temp ;

Delete elements after a specific number of nodes (n):

temp = head ;
For( i =0 ; i< n ; i++ )
{
temp = temp->next ;  //  hint : there's no something called *temp.next
}
temp = Null ;  // we usually check Temp.next = null then this is the final node

of course this topic doesn’t cover all the operations done on the linked lists , it’s all about the concept but other operations don’t contain any new concepts it’s a Mix between conditions and Pointers

for any suggestions or adds , feel free to post below  or DM me on twitter @hadyelsahar i do always check my DMs

Advertisements