Вы находитесь на странице: 1из 3

#include<iostream> using namespace std; struct Node { int data; Node *next; }*start; Node* createNode(int x) { Node *newNode;

newNode = new Node; newNode->data = x; newNode->next = NULL; return newNode; } void insert(int x) { Node *p; p = createNode(x); if(start==NULL) start=p; else if(x<=start->data) { p->next = start; start = p; } else { Node *t; t = start; while(t->next && t->next->data < x) t = t->next; p->next = t->next; t->next = p; } } void search(int x) { Node *t; t = start; while(t && t->data < x) t = t->next; if(t && t->data==x) cout<<"\nitem found.\n"; else cout<<"\nitem not found.\n"; } void remove(int x) { Node *temp, *prev; temp = prev = start; if(!start) return; if(x == start->data) {

start = start->next; delete temp; return; } while(temp->next && temp->next->data < x) temp = temp->next; if(temp->next&&temp->next->data == x) { prev = temp->next; temp->next=temp->next->next; delete prev; } else cout<<"\nitem not found\n"; } void show() { Node *t = start; while(t) { cout<<t->data<<" "; t = t->next; } } void menu() { cout<<"\n1. insert\n2. search"; cout<<"\n3. delete \n4. show\n5. exit"; cout<<"\n Enter a choice:"; } void main() { start = NULL; int choice; do{ menu(); cin>>choice; int x; switch(choice) { case 1: cout<<"Enter a number:"; cin>>x; insert(x); break; case 2: if(start){ cout<<"Enter a number:"; cin>>x; search(x); } else cout<<"\nlist is empty\n"; break; case 3: if(start){

cout<<"Enter a number:"; cin>>x; remove(x); } else cout<<"\nlist is empty\n"; break; case 4: if(start) { cout<<"\nThe linked list is:"; show(); } else cout<<"\nlist is empty.\n"; break; case 5: break; default: cout<<"\n Invalid choice.\n"; break; } }while(choice != 5); }

Вам также может понравиться