为什么我不能在链表的开头添加元素?

时间:2019-08-02 03:07:11

标签: c++ c++11 linked-list c++14 singly-linked-list

我将从C ++的数据结构和算法入手。我正在尝试将元素添加到链接列表。我写了一个代码添加到最后,它工作正常。但是,我编写了一个相当简单的代码以将元素添加到开头,但是我的代码运行成功,但是没有添加任何内容。我只想知道我要去哪里错了。

#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;
}

0 个答案:

没有答案