单链表
#include <iostream>#include <stdlib.h>#include <windows.h>using namespace std;typedef struct node{int index;struct node* next;}ListNode;typedef ListNode *LinkList;LinkList head;LinkList p;void addNode(ListNode *);void showNode();ListNode *searchByIndex(int);void initMenu();void CreateNodeList();void searchByIndexHandler();void addNode(ListNode *n){LinkList p1,p2;p1=head;p2=head->next;while(p2!=NULL){p1=p1->next;p2=p2->next;}p1->next=n;n->next=p2;}void showNode(){LinkList p;p=head->next;while(p!=NULL){cout<<p->index<<endl;p=p->next;}}ListNode *searchByIndex(int i){LinkList p;p=head->next;while(p!=NULL&&p->index!=i){p=p->next;}return p;}void initMenu(){system("cls"); int m_iOp;cout<<"1.创建单链表"<<endl;cout<<"2.根据Index查询单链表"<<endl;cout<<"3.显示全部单链表的值"<<endl;cout<<"0.退出"<<endl;cout<<"请选择:";cin>>m_iOp;switch(m_iOp){case 1:CreateNodeList();break;case 2:searchByIndexHandler();break;case 3:showNode();break;case 0:break;default:initMenu();}}void CreateNodeList(){system("cls"); cout<<"1.创建单链表:"<<endl;int sn;while(1){cout<<"请输入index值:"<<endl;cin>>sn;if (sn!=-1){p=(ListNode*)malloc(sizeof(ListNode));p->index=sn;addNode(p);}else{initMenu();}}}void searchByIndexHandler(){system("cls"); cout<<"2.根据Index查询单链表"<<endl;cout<<"输入待查询Index值:"<<endl;int sKey;cin>>sKey;LinkList pSearch=searchByIndex(sKey);if (pSearch!=NULL){cout<<pSearch->index<<endl;}else{cout<<"所查询的index不在链表中,按键返回。";char a;cin>>a;if (a==NULL){searchByIndexHandler();}}}void main(){head=(ListNode*)malloc(sizeof(ListNode));head->next=NULL;initMenu();}
页:
[1]