单链表创建及其基本操作

it2023-10-21  66

# 数据结构(单链表的创建及基本操作)## 编译工具:codeblock;

##代码写在main里面便于观察## // 单链表的创建及一些基本操作 #include <iostream> #include <string> using namespace std; /*创建一个node类用来存放data域和next域*/ class node{ public: int data; node *next; }; int main(){ node *s,*head; head=new node; head->next=NULL; /*headd->data暂空*/ 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; } /*danlist长度*/ int count1=0; for(s=head->next;s!=NULL;s=s->next){ count1++; } cout<<"................................."<<endl; /*按位查找元素 查找第i(3)位上的元素*/ 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; /*元素对比查找元素(9)返回程序执行的次数count3*/ 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;//申请插入的位置place(5),在元素5后面插上一个x(11) int x=11; int count4=count1-6; /*创建指针p用来存放data和next*/ 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老白菜

最新回复(0)