1基础-1单链表

#include
#include
using namespace std;
typedef struct Node{
    int data;
    //struct Node *prior;
    struct Node *next;
}Node;
void CreateRail(Node *head,int a[],int n){//输入链表头指针值,数组,长度
    Node *s,*r=head;//定义两个临时结点,s用于每次创建,赋给链表中的r(rail)结点
    for(int i=1;i<=n;i++){//逐个点插入
        s=(Node*)malloc(sizeof(Node));//S指向新结点
        s->data=a[i];//值赋给结点的data
        r->next=s;//把这个结点赋给链表中的结点C
        r=r->next;//r指向它的后继
    }
    r->next=NULL;//尾指针的next为空
}
void CreateFront(Node *&head,int a[],int n){//输入链表头指针引用,数组,长度
    Node* s;//定义临时结点,因为要与不断赋给头指针,所以头指针要引用传入
    for(int i=1;i<=n;i++){//逐个点插入
        s=(Node*)malloc(sizeof(Node));//S指向新结点
        s->data=a[i];//值赋给结点的data
        s->next=head->next;//头结点的后继赋给新结点
        head->next=s;//然后头结点指向新结点
    }
}
Node* Search(Node *head,int x){//输入头结点及值X,输出结点值为X的前驱
    for(Node *p=head;p->next!=NULL;p=p->next)//从头结点起扫到尾结点
        if(p->next->data==x)//如果下一结点的值就是X(要修改结点值在此处修改)
            return p;//返回结点值为X的前驱
    return NULL;//找不到就返回NULL
}
int Delete(Node *p){//输入要删除的结点的前驱
    if(p->next==NULL)//如果当前结点就是尾结点
        return 0;//返回0表示删除失败
    else{//否则
        Node *q=p->next;//读出要删除的结点
        p->next=p->next->next;//当前结点的后继指向后继的后继
        free(q);//释放要删除的结点空间
        return 1;//返回1表示删除成功
    }
}
void Insert(Node *p,int x){//输入加入结点的前驱及新增结点的值
    Node *s=(Node*)malloc(sizeof(Node));//创建新结点
    s->data=x;//赋值
    s->next=p->next;//赋后继
    p->next=s;//更新链表
}
int main(){//本例程默认是有头结点的,即第一个结点不存值
    int a[11]={0,1,3,5,7,9,2,4,6,8,10};//定义数组
    //int n;cin>>n;for(int i=0;i>a[i];
    Node *head1=(Node*)malloc(sizeof(Node));CreateRail(head1,a,10);//创建头结点并用尾插法建表
    for(Node *p=head1;p->next!=NULL;p=p->next)cout<next->data<<' ';cout<next!=NULL;p=p->next)cout<next->data<<' ';cout<next!=NULL;p=p->next)cout<next->data<<' ';cout<next,11);//在值为8的结点后加入值为11的结点
    for(Node *p=head2;p->next!=NULL;p=p->next)cout<next->data<<' ';cout<

你可能感兴趣的:(考研计机)