一个简单的链表操作程序
来源:互联网 发布:专业视频剪辑软件 编辑:程序博客网 时间:2024/05/04 16:37
这里写了个简单的链表操作函数,创建,插入和删除,另外写了个显示当前状态的display函数,这个程序实在太简单,只是实现下基本的链表操作,所以写得很粗糙,没有加如容错机制,假定一切输入都是合法的!如果你进行非法输入,那就只能看到满屏幕的数字,字符咯!呵呵!当然可以再修改下让它健壮点,呵呵!忘了说了,这个程序还有个bug,就是不能在链表头插入,所有的插入操作都将插入到某个结点的后面,所以不能插到头结点前面,当然这个操作只需稍作修改就可以了!
源程序如下:
#include<stdio.h>
#include<stdlib.h>
struct list{
int item;
struct list *next;
};
struct list *Creat(){ //创建链表函数
struct list *head,*tail,*temp;
int n;
head = tail = temp = NULL;
printf("please input the list members end with 0:/n");
scanf("%d",&n);
while(n != 0){
temp = (struct list*)malloc(sizeof(struct list));
temp ->item = n;
temp ->next = NULL;
if(head==NULL){
head = temp;
}
else
tail ->next = temp;
tail = temp;
scanf("%d",&n);
}
return head;
}
struct list *Insert(struct list *head){ //插入函数
struct list *ptr,*temp;
int m,n;
printf("please input a number you want to insert:/n");
scanf("%d",&n);
printf("behind whitch member do you want to insert:/n");
scanf("%d",&m);
temp = (struct list*)malloc(sizeof(struct list));
temp ->item = n;
temp ->next = NULL;
for(ptr=head; ptr; ptr = ptr ->next){
if(head == NULL){ //如果要插到一个空连表中
head = temp;
return head;
}
else if(ptr->item == m){
if(ptr->next == NULL){ //如果要插到最后一个成员的后面
ptr ->next = temp;
return head;
}
temp ->next = ptr->next; //插入连表中间某个成员后面
ptr ->next = temp;
return head;
}
}
printf("sorry can't find the member/n");
return head;
}
struct list *Dele( struct list *head){ //删除函数
struct list *ptr1,*ptr2;
int m;
printf("please input the member you want to delete:/n");
scanf("%d",&m);
if(head->item == m){
ptr1 = head;
head = head ->next;
free(ptr1);
return head;
}
if(head == NULL)
return NULL;
ptr1 = head;
ptr2 = head ->next;
while(ptr2){
if(ptr2->item == m){
ptr1 ->next = ptr2 ->next;
free(ptr2);
return head;
}
ptr1 = ptr2;
ptr2 = ptr2 ->next;
}
printf("no such item find!/n");
return head;
}
void Display(struct list *head){ //显示函数
struct list *ptr;
ptr = head;
printf("the list now is like this:/n");
for(ptr;ptr;ptr = ptr ->next){
printf("%d ",ptr ->item);
}
printf("/n");
}
int main(){ // main函数
struct list *head;
head = Creat();
Display(head);
Insert(head);
Display(head);
Dele(head);
Display(head);
return 0;
}
- 一个简单的链表操作程序
- 用c++写一个顺序表的简单操作程序
- 一个简单的链表程序
- 一个简单的c#+sqlserver本地操作程序
- perl一个简单mysql操作的小程序
- 简单的一个程序
- 一个简单的程序
- 一个简单的程序
- 一个简单的操作
- 简单的数据库操作程序
- 一个简单的解密程序
- 一个简单的XWindow程序
- 一个简单的端口扫描程序
- 一个简单的OpenGL程序
- 一个简单的Ajax 程序
- 一个简单的Ajax程序
- 一个简单的分页程序
- 一个简单的通讯录程序
- Transact SQL 常用语句以及函数
- Re:面试软件必备编程题
- 重构的原则
- Java类加载机制
- 用C#实现目录拷贝
- 一个简单的链表操作程序
- 能影响你的是你身边的人和你的胸怀
- Windows9x系统下汉字输入法的基本原理
- 人是不可理解的生物
- 同步杂摘
- 深入浅出java多线程
- 使用J2SE API读取Properties文件的六种方法
- 对网上流传的水波算法的质疑
- Protocol Layers and Their Service Models