21xrx.com
2024-06-03 01:04:39 Monday
登录
文章检索 我的文章 写文章
C++线性表代码实现
2023-07-04 22:24:43 深夜i     --     --
C++ 线性表 代码实现 数据结构 链表

C++线性表是指在计算机程序中使用数组或链表等方式来存储数据的一种数据结构,用来表示一组有序的数据。它支持在其中添加、删除、查找和修改数据等基本操作。

以下是C++线性表的代码实现:

首先,我们需要定义一个结构体Node,用来表示一个线性表中的节点。


struct Node {

  int val;

  Node* next;

  Node(int x) : val(x), next(NULL) {}

};

接下来,我们定义一个LinkedList类,它包含了节点的插入、删除和查找等函数。


class LinkedList {

private:

  Node* head;

public:

  LinkedList()

    head = NULL;

  

  void insert(int x) {

    Node* newNode = new Node(x);

    if (head == NULL)

      head = newNode;

     else

      newNode->next = head;

      head = newNode;

    

  }

  void remove(int x) {

    if (head == NULL)

      return;

    

    Node* prev = head;

    Node* cur = head->next;

    if (prev->val == x)

      head = head->next;

      delete prev;

      return;

    

    while (cur != NULL) {

      if (cur->val == x)

        prev->next = cur->next;

        delete cur;

        break;

      

      prev = cur;

      cur = cur->next;

    }

  }

  Node* find(int x) {

    Node* cur = head;

    while (cur != NULL) {

      if (cur->val == x)

        return cur;

      

      cur = cur->next;

    }

    return NULL;

  }

};

最后,我们可以在主函数中使用LinkedList类来创建一个线性表,并进行各种操作。


int main() {

  LinkedList list;

  list.insert(1);

  list.insert(2);

  list.insert(3);

  Node* node = list.find(2);

  if (node != NULL)

    std::cout << "Found node with value: " << node->val << std::endl;

  

  list.remove(2);

  node = list.find(2);

  if (node == NULL)

    std::cout << "Node not found" << std::endl;

  

  return 0;

}

总之,C++线性表提供了一种灵活有效的方式来存储和管理数据,能够适应各种不同的应用场景。开发者可以根据需要选择使用数组或链表实现线性表,以便更好地应对各种数据操作需求。

  
  

评论区

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