竟然从没写过链表!!!


struct
node { int num; node *next; }; node *head, *p, *q; void Init(){ head = new node(); q = head; } void Insert(int x){ //尾插x; p = new node(); p->num = x; q->next = p; q = p; q->next = NULL; } int Find(node *t, int k){ //查找第k个元素; int cnt = 1; node *p = t; p = t->next; while((p != NULL) && (cnt < k)){ p = p->next; cnt++; } return p->num; } bool Search(node *t, int x){ //查找值为x的元素是否在链表中; node *P = t; while(p != NULL){ if(p->num == x) return true; p = p->next; } return false; } void Delete(node *t, int x){ //删除值为x的元素; node *q = t,*p; p = q->next; while( p != NULL && (p->num != x)){ q = p; p = p->next; } q->next = p->next; delete p; } void Print(){ node *t = head; t = t->next; while(t != NULL){ printf("%d\n",t->num); t = t->next; } } int main(){ //freopen("in.txt","r",stdin); //freopen("out.txt","w",stdout); int n,x; cin>>n; Init(); while (n--){ cin>>x; Insert(x); } Print(); while(1){ printf("请输入要查找的数据;\t"); cin>>x; printf("%d\n",x); printf("数据是否在链表中;\t"); if(Search(head, x)) printf("YES\n\n"); else printf("NO\n\n"); printf("是否继续?请输入“YES”或“NO”\n"); string s; cin>>s; if(s == "YES") continue; else break; } return 0; }

 

posted on 2016-03-08 11:27  yoyo_sincerely  阅读(194)  评论(0编辑  收藏  举报