21xrx.com
2024-09-19 23:53:51 Thursday
登录
文章检索 我的文章 写文章
C++单链表程序代码
2023-06-26 15:56:26 深夜i     --     --
C++ 单链表 程序代码

C++单链表是一种常用的数据结构,它可以用来保存和管理一系列数据。单链表是由一系列的节点构成,在每一个节点中都包含了一个数据元素和一个指向下一个节点的链接。在C++中,我们可以使用指针来实现链表的数据结构。

下面是一个使用C++实现单链表的程序代码:


#include <iostream>

using namespace std;

//定义链表节点类

class Node {

public:

  int data; //数据域

  Node* next; //指向下一个节点的指针

  Node(int val = 0, Node* ptr = nullptr) : data(val), next(ptr) {}

};

//定义链表类

class LinkedList {

public:

  Node* head; //头节点

  LinkedList() : head(new Node) {}

  ~LinkedList() { clear(); }

  void clear(); //清空链表

  int size() const; //链表元素个数

  bool isEmpty() const; //判断链表是否为空

  void insert(int val, int pos); //在pos位置插入元素

  void remove(int pos); //删除pos位置的元素

  int get(int pos); //返回pos位置的元素

};

//清空链表

void LinkedList::clear() {

  Node* p = head;

  while (p != nullptr) {

    Node* q = p->next;

    delete p;

    p = q;

  }

  head = nullptr;

}

//链表元素个数

int LinkedList::size() const {

  int cnt = 0;

  Node* p = head->next;

  while (p != nullptr) {

    cnt++;

    p = p->next;

  }

  return cnt;

}

//判断链表是否为空

bool LinkedList::isEmpty() const

  return head->next == nullptr;

//在pos位置插入元素

void LinkedList::insert(int val, int pos) {

  if (pos < 0 || pos > size())

    cout << "插入位置不合法" << endl;

    return;

  

  Node* p = head;

  for (int i = 0; i < pos; i++)

    p = p->next;

  

  Node* newNode = new Node(val, p->next);

  p->next = newNode;

}

//删除pos位置的元素

void LinkedList::remove(int pos) {

  if (pos < 0 || pos >= size())

    cout << "删除位置不合法" << endl;

    return;

  

  Node* p = head;

  for (int i = 0; i < pos; i++)

    p = p->next;

  

  Node* tmp = p->next;

  p->next = tmp->next;

  delete tmp;

}

//返回pos位置的元素

int LinkedList::get(int pos) {

  if (pos < 0 || pos >= size())

    cout << "获取位置不合法" << endl;

    return -1;

  

  Node* p = head->next;

  for (int i = 0; i < pos; i++)

    p = p->next;

  

  return p->data;

}

//主函数

int main() {

  LinkedList* list = new LinkedList();

  //测试插入操作

  list->insert(1, 0);

  list->insert(2, 1);

  list->insert(3, 2);

  list->insert(4, 3);

  list->insert(5, 4);

  //测试获取操作

  cout << list->get(2) << endl;

  //测试删除操作

  list->remove(2);

  cout << "链表长度:" << list->size() << endl;

  delete list;

  return 0;

}

上面的程序实现了单链表的基本操作,包括清空链表、读取链表元素个数、判断链表是否为空、在指定位置插入元素、删除指定位置的元素和读取指定位置的元素。

在使用链表时,我们需要注意链表的插入和删除操作可能会涉及到边界情况,需要特别注意。同时,由于链表的设计可以支持动态增减元素,因此它在实际应用中具有很大的灵活性和可扩展性。

  
  

评论区

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