1/10
Looks like no tags are added yet.
Name | Mastery | Learn | Test | Matching | Spaced |
|---|
No study sessions yet.
Traversing a singly LL
Node* temp = head;
while (temp) {
cout << temp->data << " ";
temp = temp->next;
}
Insert node at the head of LL in O(1)
Node* n = new Node{value, head};
head = n;
Insert a node at the end of a singly linked list (no tail pointer)
void insertAtTail(Node*& head, int value) {
Node* newNode = new Node();
newNode->data = value;
newNode->next = nullptr;
if (head == nullptr) { head = newNode; return; }
Node* temp = head;
while (temp->next != nullptr) temp = temp->next;
temp->next = newNode;
}
Insert node at tail of LL with tail pointer in O(1)
Node* newNode = new Node{value, nullptr};
if (!head) {
head = rear = newNode;
} else {
rear->next = newNode;
rear = newNode;
}
Delete first node of LL
if (!head) return;
Node* temp = head;
head = head->next;
delete temp;
Delete a node with specific value
if (!head) return;
if (head->data == value) {
Node* temp = head;
head = head->next;
delete temp;
return;
}
Node* p = head;
while (p->next && p->next->data != value)
p = p->next;
if (!p->next) return;
Node* temp = p->next;
p->next = temp->next;
delete temp;
Function to find duplicates in a 2D integer array
void find_duplicates(int arr[][COLS], int rows, int cols) {
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
int current = arr[i][j];
// Compare current to all later elements
for (int r = i; r < rows; r++) {
for (int c = (r == i ? j + 1 : 0); c < cols; c++) {
if (arr[r][c] == current) {
cout << current << " is duplicated" << endl;
}
}
}
}
}
}
Insert a node at the beginning of a singly linked list.
void insertAtHead(Node*& head, int value) {
Node* newNode = new Node();
newNode->data = value;
newNode->next = head;
head = newNode;
}
Print LL
void printList(Node* head) {
while (head != nullptr) {
cout << head->data << " -> ";
head = head->next;
}
cout << "NULL" << endl;
}Insert at tail functionvoid insertAtTail(Node*& head, int value) {
Node* newNode = new Node();
newNode->data = value;
newNode->next = nullptr; // step 2
if (head == nullptr) { // step 3
head = newNode;
return;
}
Node* temp = head;
while (temp->next != nullptr) { // step 4
temp = temp->next;
}
temp->next = newNode; // step 5
}