singly linked list program
chamanEiqbal
c_cpp
a year ago
2.7 kB
5
Indexable
#include <iostream> using namespace std; class Node { public: int data; Node* next; }; Node *head = new Node(); // special node pointer. void insertAtBeginning(Node* head, int data) { Node* temp = new Node(); temp->data = data; temp->next = NULL; head->next = temp; } void insertAtEnd(Node* head, int data) { Node* temp = new Node(); Node * current = head->next; while(current->next != NULL) { current = current->next; } current->next = temp; temp->data = data; temp->next = NULL; } void display(Node* head) { Node* current = head->next; while(current != NULL) { cout << current->data << endl; current = current->next; } } void insertAtPosition(Node* head, int data, int pos) { Node* current = head->next; Node* temp = new Node(); Node* prev = new Node(); temp->data = data; if(head->next == NULL) { insertAtBeginning(head, data); } else { int i = 0; while(i < pos && current->next != NULL) { prev = current; current = current->next; i++; } if(current->next == NULL) { current->next = temp; temp->data = data; temp->next = NULL; } else { temp = prev->next; prev->next = temp; } } } void deleteAtEnd(Node* head) { Node* current = head->next; Node* prev = new Node(); while(current->next != NULL) { prev = current; current = current->next; } prev->next = NULL; free(current); } void deleteAtBeginning(Node* head) { Node* temp = new Node(); temp = head->next; head->next = temp->next; free(temp); } void deleteAtPosition(Node* head, int pos) { Node * current = head->next; Node * prev = new Node(); int i = 1; if(head->next == NULL) { cout << "Cannot delete." << endl; return; } else { while(i < pos && current->next != NULL) { prev = current; current = current->next; i++; } prev->next = current->next; free(current); } } int main() { insertAtBeginning(head,1); insertAtEnd(head,2); insertAtPosition(head, 3, 3); insertAtPosition(head, 40,4); insertAtPosition(head, 69, 5); deleteAtPosition(head, 3); display(head); return 0; }