跳到正文

剪贴板

剪贴板 mgvcr2fz

原文
剪贴板信息

剪贴板信息

收录
更新
C++
#include<bits/stdc++.h>
using namespace std;
struct node{
    int data;
    node* next;
};
//创建新节点
node* create_node(int da,node* head){
    node* newn=new node();
    newn->data=da;
    newn->next=NULL;
    return newn;
}
//添加新节点
node* append(int da,node* head){
    node* nd=create_node(da,head);
    if(!head){
        head=nd;
    }
    else{
        node* temp=head;
        for(;temp->next!=NULL;){
            temp=temp->next;
        }
        temp->next=nd;
    }
    return head;
}
//在值为p_da的一项的前面插入da
node* insert(node* head,int p_da,int da){
    node* nd=create_node(da,head);
    node* temp=head;
    node* temp2=temp;
    for(;temp->next !=NULL &&temp->data != p_da;){
        temp2=temp;
        temp= temp->next;
    }
    if (temp->next ==NULL) return head;
    else{
        if(temp==head){
            nd->next=head;
            return nd;
        }
        nd->next=temp;
        temp2->next=nd;
    }
    return head;

}

//输出链表
void print(node* head){
    node* temp=head;
    for(;temp!=NULL;){
        cout<<temp->data<<' ';
        temp=temp->next;
    }
    cout<<endl;
}
int main(){
    node* head=NULL;
    head=append(45,head);
    head=append(14,head);
    head =insert(head,45,11);
    print(head);
    return 0;
}