Advanced Algorithms & Data Structures: Lecturer: Karimzhan Nurlan Berlibekuly
Advanced Algorithms & Data Structures: Lecturer: Karimzhan Nurlan Berlibekuly
ALGORITHMS &
DATA STRUCTURES
Lecture-04
Data Structures
Single Linked List
Double Linked List
class Node {
public:
int data;
Node* next;
};
Linked List. Representation:
First Simple Linked List in C Let us create a simple linked list with 3 nodes.
#include <bits/stdc++.h>
using namespace std; // allocate 3 nodes in the heap
head = new Node();
class Node { second = new Node();
public: third = new Node();
int data;
Node* next; head->data = 1; // assign data in first node
}; head->next = second; // Link first node
with
// Program to create a simple linked
// list with 3 nodes second->data = 2;
int main() second->next = third;
{
Node* head = NULL; third->data = 3; // assign data to third
Node* second = NULL; node
Node* third = NULL; third->next = NULL;
return 0;
}
Linked List. Representation:
First Simple Linked List in C Let us create a simple linked list with 3 nodes.
head
|
|
+---+---+ +---+---+ +----+------+
| 1 | o----->| 2 | o-----> | 3 | NULL |
+---+---+ +---+---+ +----+------+
// If head node itself holds the key to be // If key was not present in linked list
deleted if (temp == NULL) return;
if (temp != NULL && temp->data == key)
{ // Unlink the node from linked list
*head_ref = temp->next; // Changed prev->next = temp->next;
head
free(temp); // free old head free(temp); // Free memory
return; }
}
Double Linked List
A Doubly Linked List (DLL) contains an extra pointer, typically
called previous pointer, together with next pointer and data
which are there in singly linked list.
Double Linked List
// Class for Doubly Linked List
public class DLL {
Node head; // head of list