21xrx.com
2024-09-20 00:23:07 Friday
登录
文章检索 我的文章 写文章
C++实现链表数据结构
2023-06-28 18:01:03 深夜i     --     --
C++ 链表 数据结构

链表是一种常见的数据结构,可以用于在内存中存储和操作大量数据。C++是一种流行的编程语言,提供了灵活的编程语言结构和强大的内存管理功能,使其成为实现链表的理想选择。

在C++中,链表可以通过自定义类来实现。这个类代表链表的每个节点,它应该包含一个指向下一个节点的指针和一个实际存储数据的成员变量。为了创建一个完整的链表,需要管理所有节点的指针,这些指针应该从链表的第一个节点开始链接到最后一个节点。

下面是一个简单的C++链表实现示例:


#include <iostream>

using namespace std;

class Node {

public:

  int data;

  Node* next;

};

class LinkedList {

public:

  LinkedList()

    head = NULL;

  

  // Add a new node to the end of the linked list

  void addNode(int n) {

    Node* newNode = new Node();

    newNode->data = n;

    newNode->next = NULL;

    if (head == NULL)

      head = newNode;

     else {

      Node* current = head;

      while (current->next != NULL)

        current = current->next;

      

      current->next = newNode;

    }

  }

  // Remove a node from the linked list

  void removeNode(int n) {

    Node* current = head;

    Node* previous = NULL;

    while (current != NULL && current->data != n)

      previous = current;

      current = current->next;

    

    if (current == NULL)

      cout << n << " not found in the list." << endl;

      return;

    

    if (previous == NULL)

      head = current->next;

     else

      previous->next = current->next;

    

    delete current;

  }

  // Print all the nodes in the linked list

  void printList() {

    if (head == NULL)

      cout << "List is empty." << endl;

      return;

    

    Node* current = head;

    while (current != NULL)

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

      current = current->next;

    

    cout << endl;

  }

private:

  Node* head;

};

int main() {

  LinkedList list;

  list.addNode(5);

  list.addNode(10);

  list.addNode(15);

  list.printList();

  list.removeNode(10);

  list.printList();

  return 0;

}

这个示例实现了一个具有基本功能的链表,包括添加节点,删除节点和打印链表。我们可以将它作为起点,进一步构建不同类型的链表,满足我们的特定需求。

总的来说,C++是实现链表数据结构的一种非常强大的编程语言。它提供了强大的内存管理功能和灵活的编程结构,可以让我们构建具有不同实现和功能的链表。无论何时,当我们需要在程序中处理大量数据时,我们都可以回来这个基本的链表实现,并将其扩展和改进,以满足我们的特定需要。

  
  

评论区

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