c/c++实现链表的各个函数和调用
#include using namespace std; typedef struct _Node { int value; struct _Node *next; }Node; typedef struct _list { Node *head; }List; void _add(List *plist,int num); void print(List *list); bool search(List *plist,int num); void ldelete(List *plist,int num); void freeall(List *list); bool insert(List *plist,int position,int num); int main() { int num,in,pos; List list; list.head = NULL; do { cin >> num; if(num!=-1) _add(&list,num); } while (num != -1); print(&list); cout << "请输入你要查找的数字=>"; cin >> in; if (search(&list,in)) cout << "找到了" << endl; else cout << "没找到" << endl; cout << "请输入你要删除的数字=>"; cin >> in; ldelete(&list,in); print(&list); cout << "请输入你要插入的位置和元素=>"; cin >> pos >> in; insert(&list,pos,in); print(&list); freeall(&list); return 0; } void _add(List *plist,int num)//新建链表 { Node *p = (Node*)malloc(sizeof(Node)); p->value = num; p->next = NULL; if (plist->head) { Node *last = plist->head; for (; last->next; last = last->next); //while (last->next) // last = last->next; last->next = p; } else plist->head = p; } void print(List *list)//打印链表 { Node *p; for (p = list->head; p; p = p->next) cout < cout << endl; } bool search(List *plist,int num)//搜索 { Node *p; for (p = plist->head; p; p = p->next) if (p->value == num) return 1; return 0; } void ldelete(List *plist,int num)//删除指定结点 { Node *p,*q=NULL; for (p = plist->head; p; q=p,p = p->next) if (p->value == num) { if (q) q->next = p->next; else plist->head = p->next; free(p); break; } } void freeall(List *list)//删除链表 { Node *p,*q; for (p = list->head; p; p = q) { q = p->next; free(p); } } bool insert(List *plist,int num) { int cnt = 1; Node *p,*q; Node *m = (Node *)malloc(sizeof(Node)); m->value = num; m->next = NULL; for (p = plist->head,q=NULL; p; q=p,p = p->next) { if (cnt == position) { if (q) { q->next = m; m->next = p; } else { m->next = plist->head; plist->head = m; } return 1; } cnt++; } return 0; } (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |
- PostgreSQL DELETE / INSERT吞吐量问题
- Objective-C:forKey和forKeyPath有什么区别?
- Ctrl+Shift+F 无法格式化xml文件
- Vue2.0 UI框架ElementUI使用方法详解
- cocos2dx 对etc1的支持
- cocos2d 移植android 5.0系统上黑屏而不闪退
- c# – DevExpress.Wpf.Grid.InfiniteGridSizeException未处
- VB之旅-数据库中表格分类查看
- 在MFC中使用纯COM方式来操纵Flash OCX (IShockwaveFlash)
- c# – 为什么在调用SqlDataReader.NextResult后没有找到数据