今天抽了点时间,复习了一下链表,总结了建立,删除,插入,查找的操作方法。
源码如下:
#include < iostream > using namespace std; typedef struct LNode { int data; struct LNode * next; }LNode, * Llist; // 方法声明 LNode * creat_head(); // 创建一个空表 void creat_list(LNode * , int ); // 创建一个长度为n的线性链表 void insert_list(LNode * , int , int ); // 插入一个元素 int delete_list(LNode * , int ); // 删除一个元素 // 创建一个空链表 LNode * creat_head() { LNode * p; p = (Llist)malloc( sizeof (LNode)); p -> next = NULL; return (p); } // 创建一个长度为n的线性链表 void creat_list(LNode * head, int n) { LNode * p, * q; int i; p = head; for (i = 1 ;i <= n;i ++ ) { q = (Llist)malloc( sizeof (LNode)); cout << " data: " ; cin >> q -> data; q -> next = NULL; p -> next = q; p = q; } } // 插入一个元素 void insert_list(LNode * head, int x, int i ) { int j = 0 ; LNode * p, * s; p = head; while ((p != NULL) && (j < i - 1 )) { p = p -> next; j ++ ; } if (p == NULL) exit( 0 ); s = (Llist)malloc( sizeof (LNode)); s -> data = x; s -> next = p -> next; p -> next = s; } // 删除一个元素 int delete_list(LNode * head, int i) { LNode * p, * q; int j = 0 ; int x; p = head; while ((p != NULL) && (j < i - 1 )) { p = p -> next; j ++ ; } if (p == NULL) exit( 0 ); q = p -> next; p -> next = q -> next; x = q -> data; delete(q); return (x); } // 输出 void Print(LNode * head,LNode * p){ for (p = head -> next;p != NULL;) { cout << p -> data << endl; p = p -> next; } } // 按序号查找 int Find(LNode * head,LNode * p, int i){ int j = 0 ; int k; for (p = head -> next;p != NULL;){ j ++ ; if (i == j) k = p -> data; p = p -> next; } return k; } // 主函数 int main() { LNode * head, * p; int find; int n; int x,i; int b; int clrscr(); head = creat_head(); cout << " 请输入链表长: " << endl; cout << " n= " ; cin >> n; cout << " 请输入数值: " << endl; creat_list(head,n); cout << " 您输入的链表为: " << endl; Print(head,p); cout << " \n请输入您要插入的数:\n " ; cout << " x= " ; cin >> x; cout << " \n请输入您要插入的位置:\n " ; cout << " i= " ; cin >> i; insert_list(head,x,i); cout << " 您输入的链表为: " << endl; Print(head,p); cout << " \n请输入您要删除的位置:\n " ; cout << " i= " ; cin >> i; b = delete_list(head,i); cout << " 删除后的链表为: " << endl; Print(head,p); cout << " 请输入您要查找的位置: " << endl; cin >> find; cout << Find(head,p,find) << endl; cout << " 请输入您要查找的位置: " << endl; cin >> find; cout << Find(head,p,find) << endl; cout << " 请输入您要查找的位置: " << endl; cin >> find; cout << Find(head,p,find) << endl; return 0 ; }
有点少,将就着看吧。转载注明:www.cnblogs.com/shiyangxt
相关资源:数据结构与算法全集(C源代码 详细注释)