首页 > 编程语言 > C++实现简单单向链表
2020
09-29

C++实现简单单向链表

本文实例为大家分享了C++实现简单单向链表的具体代码,供大家参考,具体内容如下

为了练习一下对链表的理解,尝试手动造轮子,实现单向链表的右添加,左添加和删除的功能。

头文件

#pragma once
#include<iostream>
using namespace std;
struct Node//节点
{
 int value;
 Node* next;
 Node(int a = 0, Node* n = NULL) :value(a), next(n) {}
};
class List
{
private:
 Node* head = NULL;//头指针
 Node* tail = NULL;//尾指针,便于在尾部添加节点
 int size = 0;
public:
 int getSize() { return size; }//获取链表大小
 void print();//打印链表
 void append(int a);//右添加
 void appendleft(int a);//左添加
 void remove(int a);//删除节点
};

源文件

#include "List.h"

void List::append(int a)
{
 Node *p = new Node(a);
 if (head)
 {
 tail->next = p;
 tail = p;
 }
 else
 {
 head = p;
 tail = p;
 }
 size++;
}
void List::appendleft(int a)
{
 Node *p = new Node(a);
 if (head)
 {
 p->next = head;
 head = p;
 }
 else
 {
 head = p;
 tail = p;
 }
 size++;
}
void List::remove(int a)
{
 Node* p = head;
 bool flag = false;
 if (!head)
 {
 flag = false;
 cout << "链表已空,无需删除!" << endl;
 }
 else if (head->value == a && head != tail)
 {
 head = head->next;
 delete p;
 size--;
 flag = true;
 cout << "删除成功!" << endl;
 }
 else if (head->value == a && head == tail)
 {
 head = NULL, tail = NULL;
 delete p;
 size--;
 flag = true;
 cout << "删除成功!" << endl;
 }
 else
 {
 Node*q = head->next;
 while (q)
 {
  if (q->value == a && q != tail)
  {
  p->next = q->next;
  delete q;
  size--;
  flag = true;
  cout << "删除成功!" << endl;
  break;
  }
  else if (q->value == a && q == tail)
  {
  p->next = NULL;
  tail = p;
  delete q;
  size--;
  flag = true;
  cout << "删除成功!" << endl;
  break;
  }
  else
  {
  p = q;
  q = p->next;
  }
 }
 if (!flag)
  cout << "查无此值:" << a << endl;
 }
}
void List::print()
{
 if (!head)
 cout << "链表为空,无法输出!" << endl;
 else
 {
 cout << "链表为:" ;
 Node*p = head;
 while (p)
 {
  cout << p->value << " ";
  p = p->next;
 }
 cout << endl;
 }
}

主程序验证

int main()
{
 List list1;
 list1.append(3);
 list1.append(4);
 list1.appendleft(5);
 list1.appendleft(6);
 list1.append(2);
 cout << "----链表大小:" << list1.getSize() << endl;
 list1.print();
 list1.remove(5);
 cout << "----链表大小:" << list1.getSize() << endl;
 list1.print();
 list1.remove(7);
 cout << "----链表大小:" << list1.getSize() << endl;
 list1.print();
 list1.remove(6);
 cout << "----链表大小:" << list1.getSize() << endl;
 list1.print();
 list1.remove(4);
 cout << "----链表大小:" << list1.getSize() << endl;
 list1.print();
 list1.remove(3);
 cout << "----链表大小:" << list1.getSize() << endl;
 list1.print();
 list1.remove(2);
 cout << "----链表大小:" << list1.getSize() << endl;
 list1.print();
 system("pause");
 return 0;
}

验证结果

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持自学编程网。

编程技巧