数据结构——1 单链表建立、输出和测长
2016-08-18 16:37
399 查看
单链表——建立、输出和测长
创建单链表,并输出链表,查找链表中某个结点元素,测试链表的长度(结点个数)。链表操作中一种习惯是将头结点作为第一个结点,另一种是头结点起标记作用,它后面的结点作为第一个结点,个人喜好这种方式,个人。
#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; }
相关文章推荐
- 数据结构——9 双向链表建立、输出和测长
- 数据结构基础_逆向输出链表
- 数据结构实验之链表一:顺序建立链表
- 山东理工大学oj【2116】数据结构实验之链表一:顺序建立链表
- 山东理工OJ【2121】数据结构实验之链表六:有序链表的建立(插排法)
- 数据结构实验之链表一:顺序建立链表
- 数据结构——算法之(021)( 从尾到头输出链表)
- 程序员面试宝典之数据结构基础----⑥双链表的建立,插入和删除
- 山东理工OJ【2117】数据结构实验之链表二:逆序建立链表
- 数据结构实验之链表一:顺序建立链表
- 山东理工OJ【2121】数据结构实验之链表六:有序链表的建立(插排法)
- 数据结构实验之链表一:顺序建立链表
- 2121 数据结构实验之链表六:有序链表的建立 【纯插排】
- 数据结构的单链表创建与输出
- 【程序员面试宝典】数据结构基础二单链表循环链表的操作 建立|插入删除|打印|合并
- sdut.acm2012级《程序设计基础Ⅱ)》_链表 数据结构实验之链表二:逆序建立链表
- 【学习点滴-数据结构-单链表】单链表的建立,遍历及有序单链表合并
- 数据结构实验之链表二:逆序建立链表
- 山东理工OJ【2117】数据结构实验之链表二:逆序建立链表
- 数据结构知识整理-链表的建立 逆置