链表

竟然从没写过链表!!!


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 ",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("请输入要查找的数据; "); cin>>x; printf("%d ",x); printf("数据是否在链表中; "); if(Search(head, x)) printf("YES "); else printf("NO "); printf("是否继续?请输入“YES”或“NO” "); string s; cin>>s; if(s == "YES") continue; else break; } return 0; }
原文地址:https://www.cnblogs.com/yoyo-sincerely/p/5253342.html