程序员面试宝典之数据结构基础----①单链表的建立、测长、打印(读后)
2012-10-02 21:15
351 查看
单链表的逆序(递归非递归),删除节点,插入,排序都很熟悉了,如果面试遇到,相信大家都能够写出来,但是,今天看到这个题目的时候,却花了一些时间来捉摸,不是难,二十有很多细节要注意:下面是程序员面试宝典书三上的代码,稍稍有点改动。
输出结果:
Please input the data:1
1
Please input the data:2
2
Please input the data:3
3
Please input the data:4
4
Please input the data:5
5
Please input the data:6
6
Please input the data:7
7
Please input the data:0
yyy 1 2 3 4
Now,These 7 records are:
uuu 1
uuu 2
uuu 3
uuu 4
uuu 5
uuu 6
uuu 7
Process returned 0 (0x0) execution time : 6.685 s
Press any key to continue.
#include <iostream> #include <stdio.h> #include <stdlib.h> using namespace std; //notice the define of struct, the node is not a variable,it is the name of the struct.so it can be used to define the struct variable. //notice the key word of typedef. if there is not the key word ,the node will have different properties. typedef struct student { int data; struct student* next; }node; node* creat() { node* head,*p,*s; int x=0,cycle = 1 ; head=(node*)malloc(sizeof(node)); //notice the malloc is contained in the lib of <stdlib.h> and must malloc the space for the node before you use it. p = head; while(cycle) { printf("\nPlease input the data:"); scanf("%d",&x); if(x!= 0) // only for test ,so the '0' is the symblo of the end but the value of the node,I ignore this kind of possible. Of course you can do it . { s = (node*)malloc(sizeof(node)); s->data = x; printf("\n%d",s->data); p->next = s; p = s; } else cycle = 0; } head = head->next; p->next = NULL; printf("\n yyy %d %d %d %d",head->data,head->next->data,head->next->next->data, head->next->next->next->data);//print four node for test. return(head); } int length(node* head) { int n = 0; node *p; p = head; while(p!=NULL) { p = p->next; n++; } return n; } void print(node* head) { node *p; int n; n = length(head); printf("\nNow,These %d records are:",n); p = head; if(head!= NULL) { while(p != NULL) { printf("\n uuu %d ",p->data); p = p->next; } } } int main() { node* head = creat(); print(head); }
输出结果:
Please input the data:1
1
Please input the data:2
2
Please input the data:3
3
Please input the data:4
4
Please input the data:5
5
Please input the data:6
6
Please input the data:7
7
Please input the data:0
yyy 1 2 3 4
Now,These 7 records are:
uuu 1
uuu 2
uuu 3
uuu 4
uuu 5
uuu 6
uuu 7
Process returned 0 (0x0) execution time : 6.685 s
Press any key to continue.
相关文章推荐
- 程序员面试宝典之数据结构基础----②单链表删除节点(读后)
- 程序员面试宝典之数据结构基础----单链表的逆序打印
- 【程序员面试宝典】数据结构基础二单链表循环链表的操作 建立|插入删除|打印|合并
- 程序员面试宝典之数据结构基础----⑥双链表的建立,插入和删除
- 【数据结构】单链表的建立,测长,打印,删除,插入, 排序, 逆置
- 数据结构——单链表的创建、逆置、插入、有序表的建立、有序单链表合并等基础操作!!
- 程序员面试宝典之数据结构基础----④单链表排序(读后)
- 【程序员面试宝典】数据结构基础一单链表:创建|求长|插入|删除|排序|打印|逆置
- 程序员面试宝典之数据结构基础-----③单链表的插入
- 数据结构基础(9) --单链表的设计与实现(2)之高级操作
- 第十三章 数据结构基础--单链表
- 程序员面试宝典——数据结构之单链表
- hrbust1546 基础数据结构——单链表(1)
- 程序员面试宝典 C13数据结构基础 13.1 单链表
- 程序员面试宝典之数据结构基础----队列的入队与出队
- 数据结构基础2_单链表的实现
- 数据结构基础之单链表
- 成人版java数据结构之单链表I建立和遍历
- 程序员面试宝典之数据结构基础---⑤单链表逆序的递归与非递归实现
- 数据结构基础系列——单链表的实现