Data Structure
.
Eng. Mahmmoud Ouf
Lect 04
Data Structure:
Is a way for storing, organizing and Manipulating data array
Array is type of Data Structure
array is fixed length
Linked List:
set of nodes, each node has (Data, Reference to Next node)
node
Data Data
Next Next
Type of Linked List
1) Single Linked List: Head
Data Data Data
Forward Only
Next Next Next = null Tail
Data Data Data
Backward Only
Prev = null Prev Prev
Tail
2) Double Linked List: Head
node
Data Data Data
null = Prev Next Prev Next Prev Next = null
3) Circular Linked List:
Head
Single Circular Linked List
(Forward only)
Data Data Data
Next Next Next
Tail
Single Circular Linked List Data Data Data
(Backward only)
Prev Prev Prev
Head
Double Circular Linked List node
Data Data Data
Prev Next Prev Next Prev Next
Why Linked List
Array can be used to store linear data of similar data type. But array has
the following limitation:
1) The size of array is fixed and can't expand or shrink
2) inserting a new element in array need more step, as we need to move
the data one step forward to prepare the location for the new data 1 8 5 2 7
Advantage of Linked List:
1) Dynamic size
2) Ease of Insertion / Deletion
Disadvantage of Linked List:
1) Random access is not allowed, we have to access element sequentially
starting from the first node.
2) extra memory space is required for the reference of each element
Implementation of Single Linked List Forward only Data
public class Node{
Next
public int data;
public Node Next;
}
public class SingleLinkedList{
static Node Head = null; //Reference to the first node in linkedlist
/*Create Node is used to allocate a node in the memory and fill its data, then return a
reference to the node. If it can’t allocate the node, then the returned reference will be null.*/
static Node CreateNode(int Data){
Node node = new Node();
if(node != null){
node.data = Data;
node.Next = null;
}
return node;
}//end of CreateNode method
}
/*The addNode is used to add the created node at the end of the linked list. It start by calling
CreateNode, then check if the node is allocated, so it will add it at the end. Data
The method return bool (true if the node is allocated and added, false if it couldn’t allocate the node
and it is not added)*/ Next
public static bool AddNode(int Data){
bool retval = false;
Node node;
Node temp
node = CreateNode(Data); 6
5
if(node != null){
if(Head == null){ //No List
Head = node; null
}
else { //there is a list
temp = Head;
while(temp.Next != null){
temp = temp.Next;
}// end while 9
temp.Next = node;
}//end else null
retval = true;
}//end if
return retval;
}//end of AddNode method
}//end class SingleLinkedList