You are on page 1of 2

#include <iostream> using namespace std; struct node { int data; node* next; }; node* BuildOneTwoThree() { node* head

= NULL; node* second = NULL; node* third = NULL; head = new node; // allocate 3 nodes in the heap second = new node; third = new node; head->data = 1; // setup first node head->next = second; // note: pointer assignment rule second->data = 2; // setup second node second->next = third; third->data = 3; // setup third node third->next = NULL; return head; } int length(node* list) { node* current = list; int count = 0; while(current != NULL) { count++; current = current->next; } return count; } void insertAtFront(node* & list, int data) { node *newNode = new node; newNode->data = data; newNode->next = list; list = newNode; } void insertNth(node*& headRef, int index, int data) { // position 0 is a special case if (index == 0) { insertAtFront(headRef, data); } else { node* current = headRef; for(int i = 0; i < index - 1; i++) { current = current->next;

} insertAtFront(current->next, data); } } void deleteKey(node*&head, int key) { node* nodeToDelete = head, *prevNode = NULL; while(nodeToDelete != NULL && nodeToDelete->data != key) { prevNode = nodeToDelete; nodeToDelete = nodeToDelete->next; } if (nodeToDelete != NULL) { if (prevNode != NULL) { prevNode->next = nodeToDelete->next; } else { head = nodeToDelete->next; } delete nodeToDelete; } } void printList(node*&head) { node *current = head; while(current!=NULL) { cout << current->data << " "; current = current->next; } } int main() { node *A = BuildOneTwoThree(); insertAtFront(A, 5); insertNth(A, 4, 10); cout << A->next->data << endl; cout << length(A) << endl; printList(A); cout << endl; deleteKey(A, 3); printList(A); }

You might also like