您的位置:首页 > 理论基础 > 数据结构算法

程序员面试宝典之数据结构基础----①单链表的建立、测长、打印(读后)

2012-10-02 21:15 351 查看
单链表的逆序(递归非递归),删除节点,插入,排序都很熟悉了,如果面试遇到,相信大家都能够写出来,但是,今天看到这个题目的时候,却花了一些时间来捉摸,不是难,二十有很多细节要注意:下面是程序员面试宝典书三上的代码,稍稍有点改动。
#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.
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: