21xrx.com
2024-09-19 10:05:42 Thursday
登录
文章检索 我的文章 写文章
C++ 链表代码实现
2023-07-04 22:52:23 深夜i     --     --
C++ 链表 代码实现

C++ 链表是一种常用的数据结构,在计算机编程中应用广泛。链表可以用来存储一系列的节点,每个节点包含一个数据项和指向下一个节点的指针。链表的优点在于可以非常灵活地添加和删除元素,并且内存的使用效率比数组高。下面将介绍如何使用 C++ 实现链表的代码。

首先,我们需要定义一个节点结构体,它包含两个成员变量:


struct Node {

  int data;

  Node* next;

};

其中,data 存储节点的数据,next 是一个指向下一个节点的指针。接下来,我们可以定义一个链表类,它包含指向头节点的指针和其他一些方法:


class LinkedList {

private:

  Node* head;

public:

  LinkedList()

    head = nullptr;

  

  ~LinkedList() {

    Node* current = head;

    while (current != nullptr) {

      Node* next = current->next;

      delete current;

      current = next;

    }

  }

  void addNode(int value) {

    Node* newNode = new Node();

    newNode->data = value;

    newNode->next = nullptr;

    if (head == nullptr)

      head = newNode;

     else {

      Node* current = head;

      while (current->next != nullptr)

        current = current->next;

      

      current->next = newNode;

    }

  }

  void removeNode(int value) {

    if (head == nullptr)

      return;

     else if (head->data == value) {

      Node* temp = head;

      head = head->next;

      delete temp;

    } else {

      Node* current = head;

      while (current->next != nullptr && current->next->data != value)

        current = current->next;

      

      if (current->next != nullptr) {

        Node* temp = current->next;

        current->next = current->next->next;

        delete temp;

      }

    }

  }

  void printList() {

    Node* current = head;

    while (current != nullptr)

      std::cout << current->data << " -> ";

      current = current->next;

    

    std::cout << "null" << std::endl;

  }

};

在这个类中,我们定义了构造函数和析构函数,以及 addNode、removeNode 和 printList 方法。addNode 方法用于添加节点,它首先创建一个新节点,然后将其添加到链表的末尾。如果链表为空,新节点就是头节点;否则,我们遍历到最后一个节点,再将新节点添加到最后。removeNode 方法用于删除节点,它遍历链表,找到要删除的节点并将其从链表中移除。printList 方法用于将链表打印出来,方便我们调试程序。

我们可以在主函数中创建一个 LinkedList 对象,然后调用其方法进行测试:


int main() {

  LinkedList list;

  list.addNode(1);

  list.addNode(2);

  list.addNode(3);

  list.printList(); // 输出:1 -> 2 -> 3 -> null

  list.removeNode(2);

  list.printList(); // 输出:1 -> 3 -> null

  return 0;

}

在这个例子中,我们创建了一个链表并添加了三个节点,然后打印出链表。接着,我们通过调用 removeNode 方法,删除了节点 2,并再次打印出链表,结果为 1 -> 3。

总的来说,C++ 链表是一种非常有用的数据结构,在许多实际问题中都有应用。通过学习和掌握链表的实现方法,我们可以更好地处理复杂的数据结构和算法。

  
  

评论区

{{item['qq_nickname']}}
()
回复
回复