- #include<iostream>
- using namespace std;
- struct node //node结构体,里面有一个node指针,用来指向下一个node对象
- {
- int x;
- node *next; //指向什么类型的对象,就用什么类型的指针
- };
- node* create(int n) //创建链表,参数n表示结点的个数,返回类型是结点指针node*
- {
- node *head=new node; //建立头结点
- node *p=head; //创建用于往后指的node指针
- for(int i=0;i<n;i++)
- {
- node *temp=new node; //new一个node指针
- temp->x=rand()%100;
- p->next=temp; //将p的next指向创建的temp,把新节点连接到链表后面
- p=temp; //将p指向新结点temp,即p移动到下一个节点
- }
- p->next=NULL; //创建完成后,p->next指向NULL
- return head;
- }
- int getLength(node *head) //求链表的长度,参数head表示链表的头结点,返回值是链表的长度,即结点个数
- {
- node *p;
- p=head->next; //p重新指向头结点后的那个结点,即for循环创建的第一个结点
- int len=0;
- while(p!=NULL)
- {
- len++;
- p=p->next;
- }
- return len; //返回链表结点个数,链表长度
- }
- void display(node *head) //输出链表
- {
- node *p;
- p=head->next; //p重新指向头结点后的那个结点,即for循环创建的第一个结点
- if(p==NULL)
- cout<<"NULL List";
- while(p!=NULL) //输出
- {
- cout<<p->x<<" ";
- p=p->next;
- }
- cout<<endl;
- }
- node* search(node *head,int pos)
- {
- node *p;
- p=head->next; //p重新指向头结点后的那个结点,即for循环创建的第一个结点
- while(--pos) //查找,不能用pos--
- {
- if((p=p->next)==NULL)
- {
- cout<<"incorrect position"<<endl;
- break;
- }
- }
- if(p!=NULL)
- cout<<p->x<<endl;
- return p;
- }
- int main()
- {
- node *list;
- list=create(10);
- display(list);
- cout<<"The length of list is: "<<getLength(list)<<endl;
- search(list,1);
- return 0;
- }
单链表
最新推荐文章于 2023-11-30 14:44:21 发布