Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <iostream>
- using namespace std;
- struct node {
- int val;
- node * next;
- };
- struct SLL {
- node * head;
- void init() {
- head = NULL;
- }
- void insertFirst(int val) {
- node * new_node = new node;
- new_node->val = val;
- if(head == NULL) {
- head = new_node;
- }
- else {
- new_node->next = head;
- head = new_node;
- }
- }
- void insertLast(int val) {
- node * new_node = new node;
- new_node->val = val;
- if(head == NULL) {
- head = new_node;
- }
- else if(head->next == NULL) {
- head->next = new_node;
- new_node->next = NULL;
- }
- else {
- node * tmp = head;
- while(tmp->next != NULL) {
- tmp = tmp->next;
- }
- tmp->next = new_node;
- new_node->next = NULL;
- }
- }
- void deleteFirst() {
- if(head != NULL) {
- if(head->next == NULL) {
- delete head;
- head = NULL;
- }
- else {
- node * tmp = head;
- head = head->next;
- delete tmp;
- }
- }
- }
- void deleteLast() {
- if(head != NULL) {
- if(head -> next == NULL) {
- delete head;
- head = NULL;
- }
- else {
- node * tmp = head;
- while(tmp -> next -> next != NULL) {
- tmp = tmp->next;
- }
- node * tmp2 = tmp->next;
- delete tmp2;
- tmp->next = NULL;
- }
- }
- }
- void print() {
- node * tmp = head;
- while(tmp != NULL) {
- cout << tmp->val << " --> ";
- tmp = tmp->next;
- }
- cout << endl;
- }
- };
- int main()
- {
- SLL sll;
- sll.init();
- sll.insertFirst(1);
- sll.insertFirst(2);
- sll.insertFirst(3);
- sll.print();
- sll.insertLast(4);
- sll.insertLast(5);
- sll.insertLast(6);
- sll.print();
- sll.deleteFirst();
- sll.deleteLast();
- sll.print();
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement