当调用一个新的指针时~必须要 new 不然会产生意想不到的错误 -~-
AC代码:
#include<iostream> using namespace std; typedef struct node{ int data; struct node *next; }*n; int InitList_L(n &L){ L = new node; L -> next = NULL; return 1; } int CreateList_L(n &L){ node *p,*q = L; for(int i = 1; i <= 10; i++){ p = new node; cin >> p -> data; q -> next = p; p -> next = NULL; q = q -> next; } return 1; } int GetElem_L(n &L,int a,int &res){ int nl = 0; node *p = L -> next; while(++nl != a && p) p = p -> next; if(nl != a) return 0; res = p -> data; return 1; } int LocateElem_L(n &L,int b,int &c){ node *p = L -> next; int nl = 1; while(p -> data != b && p) p = p -> next,nl++; if(p -> data != b) return 0; c = nl; return 1; } int ListInsert_L(n &L,int a,int b){ node *p = L -> next,*q = L,*s; int nl = 0; while(++nl != a && p) q = p,p = p -> next; if(nl != a) return 0; s = new node; q -> next = s; s -> data = b; s -> next = p; return 1; } int ListDelete_L(n &L,int a,int &res){ node *p = L -> next,*q = L; int nl = 0; while(++nl != a && p) q = p,p = p -> next; if(nl != a) return 0; res = p -> data; q -> next = p -> next; return 1; } void sc(n &L){ node *p = L -> next; while(p){ cout << p -> data << " "; p = p -> next; } cout << endl; } void nz(n &L){ node *p = L -> next; L -> next = NULL; while(p){ int a = p -> data; p = p -> next; if(ListInsert_L(L,1,a)); } } void mx(n &L,int &b){ node *p = L -> next; int a = 0; while(p){ if( p -> data > a) a = p -> data; p = p -> next; } b = a; } int main() { cout<<"1. 建立链表\n"; cout<<"2. 输入数据\n"; cout<<"3. 按位置查找\n"; cout<<"4. 按值查找\n"; cout<<"5. 链表的插入\n"; cout<<"6. 链表的删除\n"; cout<<"7. 输出数据\n"; cout<<"8. 链表逆置\n"; cout<<"9. 求最大值\n"; cout<<"0. 退出\n\n"; int a,o = 1; node *L; while(1){ cout << "请选择\n"; cin >> a; switch(a){ case 1 : if(InitList_L(L)) cout<<"成功建立链表!\n"; break; case 2: cout << "请输入 10 个数据\n"; if(CreateList_L(L)) cout << "输入成功\n"; break; case 3: //单链表的按序号查找 cout<<"请输入一个位置用来查找:"; cin>> a; int res; if(GetElem_L(L,a,res)) cout<<"查找成功!第"<<a<<"个数是:"<<res<<"\n\n"; else cout<<"查找失败\n\n"; break; case 4: //单链表的按值查找 cout<<"请输入一个数值用来查找:"; int b;cin>>b; int c; if(LocateElem_L(L,b,c)) cout<<"查找成功 " << b << "在第 " << c << " 个位置\n"; else cout<<"查找失败! "<<b<<" 没有找到\n\n"; break; case 5: //单链表的插入 cout<<"请输入两个数分别代表插入的位置和数值:"; int a;cin>>a>>b; if(ListInsert_L(L,a,b)) cout<<"成功将"<<b<<"插在第"<<a<<"个位置\n\n"; else cout<<"插入失败!\n\n"; break; case 6: //单链表的删除 cout<<"请输入一个位置用来删除:"; cin>>a; if(ListDelete_L(L,a,res)) cout<<"删除成功!被删除的数是:"<<res<<"\n\n"; else cout<<"删除失败!\n\n"; break; case 7: //单链表的输出 cout<<"现在链表里的数分别是:\n"; sc(L); break; case 8 : nz(L); cout << "链表逆置成功\n"; break; case 9 : mx(L,b); cout << "最大数为 " << b << endl; break; } } return 0; }