单链表的基本操作
2015-05-09 18:43
155 查看
#include<iostream> #include<stdio.h> #include<stdlib.h> #include<string> using namespace std; //定义节点结构体 typedef struct ListNod { int data; struct ListNod *next; }listnode,*linklist; //初始化链表 void Creatlist(linklist *head) { if ((*head = (linklist)malloc(sizeof(listnode)))==NULL) exit (-1); (*head)->next = NULL; } //求链表长度 int length(linklist head) { listnode *p; int count = 1; p = head->next; while (p->next != NULL) { p = p->next; ++count; } return count; } //检查链表是否为空 int listempty(linklist head) { if (head->next == NULL) return 1; else return 0; } //遍历链表 listnode *get(linklist head,int i) { listnode *p; int j=0; if (listempty(head)) return NULL; if (i < 1) return NULL; p = head; while (p->next != NULL && j < i) { p = p->next; j++; } if (j == i) return p; else return NULL; } //从链表中查找与给定元素值相同的元素在表中的位置 int find(linklist head, int e) { listnode *p; int i=1; p = head->next; while (p) { if (p->data == e) { return i; } else { p = p->next; ++i; } if (!p) return 0; } } //向链表中插入指定元素 int insert(linklist head, int i, int e) { listnode *p, *pre; int j = 0; pre = head; while (pre->next != NULL && j < i - 1) { pre = pre->next; ++j; } if (j != i - 1) { cout << "插入位置错误"; return 0; } if ((p = (listnode *)malloc(sizeof(listnode))) == NULL) exit (-1); p->data = e; p->next = pre->next; pre->next = p; return 1; } //从链表中删除指定元素 int delect(linklist head,int i, int *e) { listnode *p, *pre; int j = 0; pre = head; while (pre->next != NULL && pre->next->next != NULL) { pre = pre->next; j++; } if (j != i - 1) { cout << "删除位置错误"; return 0; } p = pre->next; *e = p->data; pre->next = pre->next; free(p); return 1; } //销毁链表 void destroy(linklist head) { listnode *p, *q; p = head; while (p->next != NULL) { q = p; p = p->next; free(q); } } int main() { int i; int a[] = { 12, 13, 14, 52, 15, 32, 56, 55,35, 45}; linklist A; listnode *p; Creatlist(&A); //初始化链表 for (i = 1; i <= sizeof(a) / sizeof(a[0]); i++) { if (insert(A, i, a[i - 1]) == 0) { cout << "插入失败"; return 0; } } //统计并输出元素 cout << "单链表A中的元素个数有" << length(A) << "个:"; for (i = 1; i <=length(A); i++) { p = get(A, i); if (p) cout << p->data << ' '; } cout << endl; //查找元素 int k; cout << "输入要查找元素:"; cin >> k; int c = find(A, k); cout << "位置是:"<< c << endl; //插入元素并显示插入后的结果 int e,j,m; cout << "输入要插入的元素和位置:"; cin >> e >> j; m = insert(A, j, e); cout << "成功" << endl; cout << "单链表A中插入元素后的元素个数有" << length(A) << "个:"; for (i = 1; i <= length(A); i++) { p = get(A, i); if (p) cout << p->data << ' '; } cout << endl; //销毁链表 cout << "是否销毁链表?" << endl; cout << "请输入‘1(销毁) or 0(不销毁)’" << endl; int w; cin >> w; switch (w) { case 1:{ destroy(A); cout << "成功!"<<endl; }; break; case 0:return 0; break; default: return 0; } return 0; }