jeudi 1 août 2019

Why I am not able to add an element at the beginning of linked list?

I am starting on Data Structures and Algorithms on C++. I am trying to add an element to a linked list. I wrote a code to add it at the end, it is working fine. However I have written a fairly simple code to add an element to the beginning, but my code is running successfully but it is not adding anything. I just want to know where I am going wrong.

#include <iostream>
using namespace std;
class Node {
 public:
  int data;
  Node* next;
};
void printList(Node* n) {
  while (n != NULL) {
    cout << n->data << " ";
    n = n->next;
  }
  std::cout << '\n';
}

void addListlast(Node* n, int element) {
  Node* n1 = NULL;
  Node* n2 = NULL;
  n2 = n;
  n1 = new Node();
  while (n2 != NULL) {
    if (n2->next == NULL) {
      n2->next = n1;
      n1->data = element;
      n1->next = NULL;
      break;
    }
    n2 = n2->next;
  }
}
void addListfirst(Node* n, int element) {
  Node* n1 = NULL;
  n1 = new Node();
  Node* n0 = NULL;
  n0 = new Node();
  n1->data = element;
  n1->next = n;
  n = n1;
}
int main() {
  Node* head = NULL;
  Node* second = NULL;
  Node* third = NULL;

  head = new Node();
  second = new Node();
  third = new Node();

  head->data = 1;
  head->next = second;
  second->data = 2;
  second->next = third;
  third->data = 3;
  third->next = NULL;

  printList(head);
  addListlast(head, 4);
  printList(head);
  addListfirst(head, 5);
  printList(head);
  return 0;
}

Aucun commentaire:

Enregistrer un commentaire