1基础-1单链表

#include<iostream>
#include<stdlib.h>
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<n;i++)cin>>a[i];
    Node *head1=(Node*)malloc(sizeof(Node));CreateRail(head1,a,10);//创建头结点并用尾插法建表
    for(Node *p=head1;p->next!=NULL;p=p->next)cout<<p->next->data<<' ';cout<<endl;//观察链表
    Node *tmp1=Search(head1,9);Delete(tmp1);//删除链表中值为9的结点
    for(Node *p=head1;p->next!=NULL;p=p->next)cout<<p->next->data<<' ';cout<<endl;//观察链表
    Node *head2=(Node*)malloc(sizeof(Node));CreateRail(head2,a,10);//创建头结点并用头插法建表
    for(Node *p=head2;p->next!=NULL;p=p->next)cout<<p->next->data<<' ';cout<<endl;//观察链表
    Node *tmp2=Search(head2,8);Insert(tmp2->next,11);//在值为8的结点后加入值为11的结点
    for(Node *p=head2;p->next!=NULL;p=p->next)cout<<p->next->data<<' ';cout<<endl;//观察链表
    return 0;
}
/***output
1 3 5 7 9 2 4 6 8 10
1 3 5 7 2 4 6 8 10
1 3 5 7 9 2 4 6 8 10
1 3 5 7 9 2 4 6 8 11 10
***/
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值