您的位置:首页 > 其它

开始C的学习,从基础做起。

2009-04-13 17:30 190 查看
看了李先静的系统程序员成长计划(http://blog.csdn.net/absurd/category/474960.aspx?PageNumber=5)觉得很有道理,打好基础对以后很有好处,高层的东西再怎么变估计也是万变不离其宗,所以打算按照他的成长计划,看看是否能坚持。

先用C实现一个双向链表。

#include <stdio.h>
#include <malloc.h>
#include <stdlib.h>
#include <string.h>
#include <conio.h>
#define N 10

typedef struct DListNode {
char name[20];
struct DListNode *pre_link,*next_link;
} Stud;

Stud * create(int stud_number){

Stud *p,*h,*s;
int i;
if ((h = (Stud *)malloc(sizeof(Stud))) == NULL) {
printf("cant malloc more memory/n");
exit(0);
}
h->name[0] = '/0';
h->next_link = NULL;
h->pre_link = NULL;
p = h;
for(i = 0;i < stud_number;i++){

if ((s = (Stud *)malloc(sizeof(Stud))) == NULL) {
printf("can't malloc more memory/n");
exit(0);
}
p->next_link = s;
printf("please input the %d name:",i+1);
scanf("%s",s->name);
s->pre_link = p;
s->next_link = NULL;
p = s;
}
h->pre_link = s;
s->next_link = h;
return(h);
}

Stud * search(Stud *head,char *search_name){
Stud *result;
char *result_name;
result = head->next_link;
while (result != head) {
result_name = result->name;
if (strcmp(result_name,search_name) == 0) {
return(result);
}
else
result = result->next_link;
}
printf("can't search result/n");
return NULL;

}

void insert(Stud *stud_info){
Stud *new_stud;
char new_stud_name[20];
if ((new_stud = (Stud *)malloc(sizeof(Stud))) == NULL) {
printf("can't malloc more memory");
exit(0);
}
printf("please input new Stud name: ");
scanf("%s",new_stud_name);
strcpy(new_stud_name,new_stud->name);
new_stud->pre_link = stud_info;
new_stud->next_link = stud_info->next_link;
stud_info->next_link = new_stud;
(new_stud->next_link)->pre_link = new_stud;

}

void del(Stud *del_stud){
(del_stud->pre_link)->next_link = del_stud->next_link;
(del_stud->next_link)->pre_link = del_stud->pre_link;
free(del_stud);

}

void print_all(Stud *head){
Stud *next;
next = head->next_link;
printf("print all Stud info:/n");
while (next != head) {
printf("%s ",&*(next->name));
next = next->next_link;
}
printf("/n");
}

void main(){
int number;
char stud_name[20];
Stud *head,*search_stud;
number = N;
//clrscr();
head = create(number);
getch();
print_all(head);
getch();
printf("input search name:");
scanf("%s",stud_name);
search_stud = search(head,stud_name);
getch();
printf("search Result:%s/n",search_stud->name);
del(search_stud);
getch();
printAll(head);
getch();
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: