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 x) {
- node * tmp_node = new node;
- tmp_node->val = x;
- if(head == NULL) {
- head = tmp_node;
- }
- else {
- tmp_node->next = head;
- head = tmp_node;
- }
- }
- void insertLast(int x) {
- node * tmp_node = new node;
- tmp_node -> val = x;
- if(head == NULL) {
- head = tmp_node;
- }
- else {
- node * tmp = head;
- while(tmp->next != NULL) {
- tmp = tmp->next;
- }
- tmp->next = tmp_node;
- }
- }
- 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;
- node *prev;
- while(tmp->next != NULL) {
- prev = tmp;
- tmp = tmp->next;
- }
- prev->next = NULL;
- delete tmp;
- }
- }
- }
- void deleteAll() {
- while(head != NULL) {
- deleteFirst();
- }
- }
- void print() {
- node * tmp = head;
- while(tmp != NULL) {
- cout << tmp->val << " --> ";
- tmp = tmp -> next;
- }
- cout << endl;
- }
- bool deleteNode(int x) {
- if(head != NULL and head->val == x) {
- deleteFirst();
- return true;
- }
- node *tmp = head;
- node *prev = NULL;
- while(tmp != NULL and tmp->val != x) {
- prev = tmp;
- tmp = tmp->next;
- }
- if(tmp != NULL and tmp->val == x and tmp->next == NULL) {
- deleteLast();
- return true;
- }
- if(tmp != NULL and tmp->val == x) {
- prev->next = tmp->next;
- delete tmp;
- return true;
- }
- return false;
- }
- };
- void func(SLL & sll, int x) {
- while(sll.deleteNode(x)) {
- }
- sll.print();
- }
- int main() {
- int n;
- cin >> n;
- SLL sll;
- sll.init();
- for(int i = 0; i < n; i++) {
- int x;
- cin >> x;
- sll.insertLast(x);
- }
- sll.print();
- int number;
- cin >> number;
- func(sll, number);
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement