本文实例为大家分享了C++实现简单单向链表的具体代码,供大家参考,具体内容如下
为了练习一下对链表的理解,尝试手动造轮子,实现单向链表的右添加,左添加和删除的功能。
头文件
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
|
#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"
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
|
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; } } |
主程序验证
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
|
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; } |
验证结果
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持服务器之家。
原文链接:https://blog.csdn.net/weixin_42333471/article/details/88246648