Insert delete operation for single-linked list (C + + implementation)

Source: Internet
Author: User

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)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.