我是靠谱客的博主 拼搏寒风,这篇文章主要介绍单链表的基本操作——c++(有详细注解),现在分享给大家,希望可以做个参考。

呕心沥血
千辛万苦
凌晨一点仍在调试
上辈子连环杀人,这辈子软件工程
无语住了

复制代码
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
106
107
108
109
110
111
112
113
114
115
116
117
118
119
#include<iostream> typedef struct LNode{ int date; struct LNode *next; }LNode,*LinkList;//创造一个链表 bool InitList(LinkList &L); void CreateList(LinkList &L,int n); void PrintList(LinkList L); void FoundList(LinkList L,int e); void InsertList(LinkList &L,int i,int e); void DeleteList(LinkList &L,int i); using namespace std; int main() { int n,e,insertn,inserte,deleten; LinkList L; InitList(L); cout<<"请输入单链表长度:"; cin>>n; CreateList(L,n); PrintList(L); cout<<"请输入要查找的值:"; cin>>e; FoundList(L,e); cout<<"请输入要插入的位置:"; cin>>insertn; cout<<"请输入要插入的值:"; cin>>inserte; InsertList(L,insertn,inserte); cout<<"请输入要删除的位置:"; cin>>deleten; DeleteList(L,deleten); return 0; } bool InitList(LinkList &L) { L=new LNode; L->next=NULL; return true;//bool型对单链表进行初始化 } void CreateList(LinkList &L,int n) { LinkList r,p;//定义链表 L=new LNode; L->next=NULL; r=L;//对r链表进行初始化 cout<<"请输入单链表:"; for(int i=0;i<n;i++) { p=new LNode; cin>>p->date; p->next=NULL;//对怕p结点初始化 r->next=p;//使r的指针域指向p r=p;//使r=p,然后接受下一个p的结点 }//建立单链表,后插法 } void PrintList(LinkList L) { LinkList p; p=L->next; cout<<"单链表为:"; while(p) { cout<<p->date<<" ";//打印链表p的值 p=p->next;//使p指向链表的下一个位置,直到NULL } cout<<endl;//打印单链表 } void FoundList(LinkList L,int e) { LinkList p; p=L->next; int count=0; while(p) { count++;//查找一次count+1 if(p->date==e) { cout<<"第"<<count<<"次找到了与"<<e<<"相等的值"; } p=p->next;//使p指向下一个位置,,直到NULL } if(count==0) { cout<<"没有找到与"<<e<<"相等的值"; } }//查找e的值,并输出第几次查找到 void InsertList(LinkList &L,int i,int e) { LinkList p,s; p=L; int count=0; while(p&&(count<i-1)) { p=p->next;//p指向的使i-1的位置 count++; } s=new LNode;//创建一个新结点 s->date=e;//给s结点的数据域赋值 s->next=p->next;//将p指向原i位置的指针域赋给s结点,使s结点的指针域指向的是原i位置的结点 p->next=s;//使p的下一个位置(也就是i位置)为s PrintList(L); }//在i的位置插入一个e值 void DeleteList(LinkList &L,int i) { LinkList s; LinkList p=L; int count=0; while(p&&(count<i-1)) { p=p->next; count++; } s=p->next;//s指向i位置结点 p->next=s->next;//s的下一个就是i+1个结点//s->next->next delete s; PrintList(L); }//删除i位置的结点

最后

以上就是拼搏寒风最近收集整理的关于单链表的基本操作——c++(有详细注解)的全部内容,更多相关单链表内容请搜索靠谱客的其他文章。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(54)

评论列表共有 0 条评论

立即
投稿
返回
顶部