单向链表:

#include <iostream>
using namespace std;
/* 创建一个单链表 */
struct Node{
    int data;
    Node *next;
};
void creatateList(Node *head,int arr[],int n){
    Node *p=head;
    for(int i=0;i<n;i++){
        Node *pnewNode=new Node;
        pnewNode->data=arr[i];
        pnewNode->next=NULL;
        p->next=pnewNode;
        p=pnewNode;
    }
}
void Listprintf(Node *head){
    Node *p=head->next;
    while(p!=NULL){
        cout<<p->data<<" ";
        p=p->next;
    }
    cout<<endl;
}
//插入元素 
Node *insert(Node *head,int num){
    Node *p=head;
    Node *p1,*p2;
    p1=new Node;
    p2=new Node;
    p1->data=num;
    while(p1->data>p->data&&p!=NULL){
        p2=p;
        p=p->next;
    }
    if(p1->data<=p->data){
        if(p==head){
            p1->next=p;
            head=p1;
        }else {
            p1->next=p;
            p2->next=p1;
        }
    }else {
        p->next=p1;
        p1->next=NULL;
    }
    return head;
}
//删除元素
Node *deleteList(Node *head,int num){
    Node *p=head,*p1,*p2;
    p1=new Node;
    p2=new Node;
    p1->data=num;
    while(p1->data!=p->data&&p->next!=NULL){
        p2=p;
        p=p->next;
    }
    if(p1->data==p->data){
        if(p==head){
            head=p->next;
            delete p;
        }else {
            p2->next=p->next;
            delete p;
        }
    }else {
       cout<<num<<"No find"<<endl;
    }
    return head;

//释放空间
void cleanList(Node *head){
    while(head->next!=NULL){
    Node *p= head->next;
    delete head;
        head=p; 
        
    }

int main()
{
    Node *head=NULL;
    head =new Node;
    head->data=0;
    head->next=NULL; 
    int n=10;
    int a[n];
    for(int i=0;i<10;i++)a[i]=(i+1)*(i+1);
    creatateList(head,a,10);
    Listprintf(head);
    head=insert(head,30);
    Listprintf(head);
    head = deleteList(head,25);
    Listprintf(head);
        head = deleteList(head,454);
    Listprintf(head);
    return 0;
 } 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值