Linked List - Intro
- A linked list is a linear data structure where elements (nodes) are connected using pointers.
- Each Node contains:
- Data (value)
- Pointer to the next node (next)
Node Structure
class Node {public: int data; Node* next;
Node(int data) { this->data = data; this->next = NULL; }};data:stores the value.next:pointer to the next node.- Constructor initializes
dataand setsnexttoNULL.
#include <bits/stdc++.h>using namespace std;
class Node { public: int data; Node* next;
Node(int data) { this->data = data; this->next = NULL; }};
int main() { Node head(10);
Node head2(20); head.next = &head2;
cout << head.data << " & " << head.next->data << endl;
Node *head3 = new Node(30); cout << head3->data << endl;
return 0;}- Creates a node
headwith data = 10,next = NULL. - Creates another node
head2with data = 20. - Links
headtohead2→ a two-node chain:
head (10) -> head2 (20)
-
Outputs: 10 & 20 (head’s data and the data of the next node)
-
Dynamically creates a node with data = 30.
-
Outputs: 30