# 数据结构(单链表的创建及基本操作)## 编译工具:codeblock;
##代码写在main里面便于观察##
#include
<iostream
>
#include
<string
>
using namespace std
;
class node{
public:
int data
;
node
*next
;
};
int
main(){
node
*s
,*head
;
head
=new node;
head
->next
=NULL;
int arr
[]={1,2,3,9,6,7,8};
for(int i
=0;i
<7;i
++){
s
=new node;
s
->data
=arr
[6-i
];
s
->next
=head
->next
;
head
->next
=s
;
}
cout
<<"单链表的一些操作"<<endl
;
cout
<<"................................"<<endl
;
for(s
=head
->next
;s
!=NULL;s
=s
->next
){
cout
<<s
->data
<<endl
;
}
int count1
=0;
for(s
=head
->next
;s
!=NULL;s
=s
->next
){
count1
++;
}
cout
<<"................................."<<endl
;
int count2
=count1
-6;
for(s
=head
->next
;s
!=NULL;s
=s
->next
){
if(count2
>7){
throw "异常!!!";
}else if(count2
==3){
cout
<<"第3号上的元素="<<s
->data
<<endl
;
break;
}else{
count2
++;
}
}
cout
<<"................................."<<endl
;
int count3
=count1
-6;
for(s
=head
->next
;s
!=NULL;s
=s
->next
){
if(s
->data
==8){
cout
<<"元素(9)在程序执行了"<<7<<"次后,被找到!"<<endl
;
return 0;
}else if(s
->data
==9){
cout
<<"元素(9)在程序执行了"<<count3
<<"次后,被找到!"<<endl
;
break;
}else {
count3
++;
}
}
cout
<<"................................."<<endl
;
int place
=5;
int x
=11;
int count4
=count1
-6;
node
*p
;
p
=new node;
p
->next
=NULL;
p
->data
=x
;
for(s
=head
->next
;s
!=NULL;s
=s
->next
){
if(count4
>7){
throw "异常!!!";
}else if(count4
==place
){
p
->next
=s
->next
;
s
->next
=p
;
break;
}else{
count4
++;
}
}
for(s
=head
->next
;s
!=NULL;s
=s
->next
)
cout
<<"新链表:"<<s
->data
<<endl
;
}
小编:AK老白菜
转载请注明原文地址: https://lol.8miu.com/read-10402.html