Portfolio Chapter 5
Portfolio Chapter 5
contiguous memory locations. The elements in a linked list are linked using
pointers. In simple words, a linked list consists of nodes where each node contains
a data field and a reference(link) to the next node in the list.
The node contains a pointer to the next node means that the node stores the address
of the next node in the sequence. A single linked list allows the traversal of data
only in one way.
--------------- ----------- ---------
head -> - a next 1002- -> - b 1003 - -> - c 1004 - -> NULL
- data 1001 - - 1002 - - 1003 - 1004
------------------ ------------ ----------
// C++ program to illustrate creation
// and traversal of Singly Linked List
#include <bits/stdc++.h>
using namespace std;
// Structure of Node
class Node {
public:
int data;
Node* next;
};
// Driver Code
int main()
{
Node* head = NULL;
Node* second = NULL;
Node* third = NULL;
printList(head);
return 0;
}
Therefore, it contains three parts of data, a pointer to the next node, and a
pointer to the previous node. This would enable us to traverse the list in the
backward direction as well.
#include <bits/stdc++.h>
using namespace std;
// Driver Code
int main()
{
// Start with the empty list
Node* head = NULL;
// Insert 6.
// So linked list becomes 6->NULL
push(&head, 6);
While traversing a circular linked list, we can begin at any node and traverse the
list in any direction forward and backward until we reach the same node we started.
Thus, a circular linked list has no beginning and no end.
#include <bits/stdc++.h>
using namespace std;
*head_ref = ptr1;
}
// Driver Code
int main()
{
// Initialize list as empty
Node* head = NULL;
// Function call
printList(head);
return 0;
}
Insertion at the beginning of the circular linked list takes O(1) time complexity.
Traversing and printing all nodes in the circular linked list takes O(n) time
complexity where n is the number of nodes in the linked list.
Therefore, the overall time complexity of the program is O(n).