The following code implements the sequential insertion of a single-linked list, the deletion of linked list elements, the output of a linked list
//Mylink.h code#ifndefMylink_h#defineMylink_h#include<iostream>using namespace std;struct node{intData; Node*Next;}; ClassList{ Public:List() {Head=NULL; };voidInsert (int item);voiddel (int item);voidShow ();Private: node*Head;};void List:: Insert(int item)//Insert by order{Node*P=NewNode (); P -Data=Item P -Next=NULL;if(Head==NULL)//When the list is empty{Head=P }Else{Node*Q*R Q=Head while(q&&Q -Data<=P -Data) {R=Q Q=Q -Next }if(q!=NULL) {P -Next=Q R -Next=P }Else{p -Next=NULL; R -Next=P } }}void List::d el(int item) {if(Head==NULL) {cout<<"The linked list is empty and cannot be deleted"<<Endl }Else if(Head -Data==Item) {Head=Head -Next }Else{int flag=1; while(flag)//Ensure that all data in the linked list is deleted with item value{Node*P=Head Node*Q while(p&&P -Data!=Item) {Q=P P=P -Next }if(p)//Find the element in the linked listQ -Next=P -NextElseFlag=0; } }}void List:: Show() {node*P P=Headif(Head==NULL) {cout<<"Linked list is empty"<<Endl }Else{cout<<"single-linked list:"; while(p) {cout<<P -Data<<" "; P=P -Next } cout<<Endl }}#endif
Main program
Main. cppCode#include "mylink.h"#include <iostream>Using namespaceSTD;int main () {list L;L. Insert(1);L. Insert(3);L. Insert(2);L. Insert(5);L. Insert(2);L. Insert(3);L. Show();L. del(2);cout<<"After deleting element 2:"<<endl;L. Show();L. del(3);cout<<"After deleting element 3:"<<endl;L. Show();cout<<"OK"<<endl;System"Pause");Return0;}
Insert delete operation for single-linked list (C + + implementation)