链表的简单操作

    技术2022-06-24  46

    #include<iostream>using namespace std;typedef struct node{    int num; node * next;}Node;        int  insert(Node *head,int m){    int flag=1;     Node *n=head,*n1;  Node *p=new node;  p->num=m;  p->next=NULL; if(n->num > p->num)  {      n->num=p->num-1;  }

     while(n!= NULL && n->num < p->num) {                               n1=n;      n=n->next;               }                    n1->next=p;    p->next=n;   return flag;}

    int findlist(Node * head,int m){   Node  *n=head;   while(n->next != NULL)   {       if(n->next->num == m)    return 1;   n=n->next;   }    return 0;}

    int delete_(Node * head,int m){          Node * n=head,*n1; int flag=0; if(head->next == NULL) {  cout<<"该链表为空链表,不能删除"; } while(n !=NULL && n->num != m){       n1=n;  n=n->next; }if(n!=NULL){  if(n->num == m){     n1->next=n->next;  delete n;  flag=1;        cout<<m<<"已经被删除了!"<<endl;   }  else     flag=0;   } return flag ;}/*打印菜单指令*/void instructions(void){cout<<"Enter your choice:"<<endl<<"1 插入一个元素到链表中./n"<<"2 从链表中删除一个数./n"<<"3  输入一个数查找是否存在./n"<<"4  查看链表长度./n"<<"5  结束退出./n"<<endl;

    }

    void print(Node * head){   Node *no=head->next;   cout<<"当前链表数为:"<<endl;   while(no->next != NULL){        cout<<no->num<<"-->";          no=no->next;   }   cout<<no->num<<endl;}int isEmpty(Node *head){   if(head->next == NULL)    return 1;   else return 0;

    }int listLength(Node *head){    int len=0; Node * n=head; while(n->next!=NULL) {   n=n->next;   len++; } return len;}

    int main(){   system("color 4e");  Node *head=new node;  head->next=NULL;int choice;int item,item1;instructions();/*显示菜单函数*/cout<<"请选择:";cin>>choice;while( choice!=5){  switch(choice)  {  case 1:    cout<<"请输入你想要插入的链表数:"; cin>>item; if(insert(head,item)) { cout<<item<<"已经成功顺序地插入链表中!"<<endl; }    print(head);  break;   case 2:   if(!isEmpty(head)){   cout<<"请输入你要删除的数";   cin>>item;      if(delete_(head,item)){   cout<<item<<"被删除!"<<endl;   print(head);   }   else{    cout<<item<<"没有找到!"<<endl;     print(head);   }   }      else cout<<"链表为空,请先输入链表数,再查找!"<<endl;     break;  case 3:     if(!isEmpty(head)){   cout<<"Enter character to be found:";   cin>>item1;   if(findlist(head,item1))    cout<<"恭喜你,查找成功!"<<endl;  else cout<<item1<<" 没有被找到!"<<endl;  } else cout<<"链表为空."<<endl;    break;  case 4:   cout<<"这个链表的长度为: "<<listLength(head)<<endl;    break;  case 5:   cout<<"结束运行!";   exit(0);  break;

      default :   cout<<"Invalid choice."<<endl;   instructions();} cout<<"请选择:"; cin>>choice;}cout<<"结束运行."<<endl;return 0;}

    花了好些时间写了,总是感觉收获了! 但是收获什么就不知道了。我的数据结构还是要慢慢地学习了!加油!


    最新回复(0)