单链表的实现:增删改查
2011-07-29 18:08
330 查看
/* *@author ? *@since 2011/07/29 *@function 实现链表的常用操作,比较粗糙。 * 功能大概是:显示链表结构;查询链表;删除节点;插入结点;修改结点 */ #include <stdio.h> #include <stdlib.h> struct node { int value; struct node *next; }; /* *插入结点(单个) */ struct node *add_to_list(struct node *list,int n) { struct node *new_node; new_node=malloc(sizeof(struct node)); if(new_node==NULL) { printf("Error:malloc failed in add_to_list\n"); exit(EXIT_FAILURE); } new_node->value=n; new_node->next=list; return new_node; } /* *添加结点(多个) */ struct node *read_numbers(void) { struct node *first=NULL; int n; printf("Enter a series of integers (0 to terminate): "); for(;;) { scanf("%d",&n); if(n==0) { return first; } first=add_to_list(first,n); } } /* *搜索结点 */ struct node *search_list(struct node *list,int n) { struct node *p; for(p=list;p!=NULL;p=p->next) if(p->value==n) return p; return NULL; } /* *删除结点 */ struct node *delete_node(struct node *list,int n) { struct node *cur,*prev; for(cur=list,prev=NULL; cur!=NULL&&cur->value!=n; prev=cur,cur=cur->next) ; if(cur==NULL) { return list; } if(prev==NULL) { list=list->next; }else { prev->next=cur->next; } free(cur); return list; } /* *修改结点 */ struct node *update_node(struct node *list,int n) { struct node *cur; int new_value; for(cur=list;cur!=NULL&&cur->value!=n;cur=cur->next) ; if(cur==NULL) { printf("NO NODE!!!"); } printf("please enter the new value: "); scanf("%d",&new_value); cur->value=new_value; return list; } /* *打印链表结点结构 */ void print(struct node *list) { struct node *p; printf("The current relation of the list is "); for(p=list;p!=NULL;p=p->next) { if(p->next!=NULL) { printf("%d->",p->value); }else { printf("%d\n",p->value); } } } int main() { struct node *test,*p; int n; test=read_numbers(); /* *输出当前链表 */ print(test); /* *查找链表中结点,并输出结点的值 */ printf("Please enter the value to look for: "); scanf("%d",&n); p=search_list(test,n); printf("The value of the node is %d\n",p->value); /* *删除结点并显示更新后链表的结构 */ printf("Please choose the value of the node you would like to delete: "); scanf("%d",&n); p=delete_node(test,n); print(p); /* *修改结点并显示更新后链表的结构 */ printf("Please choose the value of the node you would like to update: "); scanf("%d",&n); p=update_node(test,n); print(p); return 0; }
结果如下:
相关文章推荐
- C++链表的增删改查实现原理
- 用java手动实现一个链表的增删改查
- 数据结构(二):Java实现:链表实现增删查操作(具有头结点)
- 单链表的增删查改(C++实现)
- java实现简单链表(int类型)增删查
- JAVA实现双向链表的增删功能的方法
- 【C】利用单链表数据结构实现通讯录,链表的增删改查
- JAVA实现双向链表的增删功能
- Java实现单向链表的增删改查
- 单链表的增删排序求长度的实现。
- 数据结构之链表的增删操作的Java实现
- 用java实现双向循环链表的增删改查
- 实现单链表中的增删查改(2)
- C语言实现单链表增删查找等功能
- JAVA实现单向链表的增删操作
- 自己用c语言结构体实现一个链表结构体(增删查改)
- 自己写了一个链表功能还不完善但是简单的增删改查功能都已经实现了
- c语言-指针实现链表增删改查
- 在学习中对于链表的实现。链表的增删查改等操作(C语言版)
- 用C++实现双链表的增删查改以及双向链表的逆转