#include <iostream>
#define OK 1
#define ERROR 0
#define VOERFLOE -2
using namespace std; typedef int Status;
typedef struct LNode
{ int date; struct LNode * next;
} LNode, * LinkList;
Status InitList ( LinkList & L)
{ L= new LNode; L- > next= NULL ; return OK;
}
void CreatList ( LinkList & L, int n)
{ L= new LNode; L- > next= NULL ; for ( int i= 0 ; i< n; i++ ) { LinkList p; p= new LNode; cin>> p- > date; p- > next= L- > next; L- > next= p; }
}
Status GetNumber ( LinkList & L, int i, int & e)
{ LinkList p; int j= 1 ; p= L- > next; while ( p&& j< i) { p= p- > next; ++ j; } if ( ! p|| j> i) return ERROR; e= p- > date; return OK;
}
LNode * LocateNumber ( LinkList & L, int e)
{ LinkList p; p= L- > next; while ( p&& p- > date!= e) { p= p- > next; } return p;
}
int ListInsert ( LinkList & L, int i, int e)
{ LinkList p; int j= 0 ; p= L; while ( p&& ( j< i- 1 ) ) { p= p- > next; ++ j; } if ( ! p|| j> i- 1 ) return ERROR; LNode * s= new LNode; s- > date= e; s- > next= L- > next; L- > next= s; return OK;
}
Status ListDelete ( LinkList & L, int i)
{ LinkList p, q; int j= 0 ; p= L; while ( p- > next&& ( j< i- 1 ) ) { p= p- > next; ++ j; } if ( ( ! p- > next) || ( j> i- 1 ) ) return ERROR; q= p- > next; p- > next= q- > next; delete q; return OK;
}
void display ( LinkList & L)
{ LNode * p; p= L- > next; while ( p- > next) { cout<< p- > date<< "->" ; p= p- > next; } cout<< p- > date;
}
void welcome ( )
{ cout<< "1.初始化\n" ; cout<< "2.输入\n" ; cout<< "3.取值\n" ; cout<< "4.查找\n" ; cout<< "5.插入\n" ; cout<< "6.删除\n" ; cout<< "7.输出\n" ; cout<< "0.退出\n" ; cout<< endl;
} int main ( )
{ LinkList L; welcome ( ) ; bool a= true ; while ( a) { int N; cout<< endl<< "请选择:" ; cin>> N; switch ( N) { case 1 : { InitList ( L) ; cout<< "成功构建一个空的单链表!" ; break ; } case 2 : { int n; cout<< "请输入单链表长度:" ; cin>> n; cout<< "请逆序输入单链表元素:" ; CreatList ( L, n) ; cout<< "单链表创建成功!" ; break ; } case 3 : { int i, e; cout<< "请输入所取元素位置:" ; cin>> i; if ( GetNumber ( L, i, e) ) { cout<< "取值成功,值为:" ; cout<< e; } break ; } case 4 : { int e; cout<< "请输入所要查找的元素:" ; cin>> e; LocateNumber ( L, e) ; cout<< "元素的位置是:" << e; break ; } case 5 : { int i, e; cout<< "请输入位置i:" ; cin>> i; cout<< "请输入插入元素:" ; cin>> e; if ( ListInsert ( L, i, e) ) { cout<< "插入成功!" ; } break ; } case 6 : { int i; cout<< "请输入要删除的位置i:" ; cin>> i; if ( ListDelete ( L, i) ) { cout<< "删除成功!" ; } } case 7 : { cout<< "链表元素为:" ; display ( L) ; break ; } case 0 : { a= false ; } } } return 0 ;
}