链表的c语言实现

#include <iostream>
#include <queue>
#include <map>
#include <stdio.h>
#include <stdlib.h>
using namespace std;

struct node
{
        int data;
        struct node *next;
};
//利用头插法
node * creatnode();//产生一个头节点
void insertnode(node * L,int x);//插入一个值x 的数据
void deletenode(node * L);//删除一个值x 的数据
void printnode(node *L);//遍历输出链表的内容
int  searchnode(node *L, int x);//返回值为x 的位置,可以修改返回类型和返回值使其为指针
void alternode (node *L,int x,int xx);//将x替换为xx
int main()
{
        int n;
        int num;
        cin>>n;
        node *L;
        L=creatnode();
        for(int i=0;i<n;i++)
        {

                cin>>num;
                insertnode(L,num);

        }
        printnode(L);
    return 0;
}
node * creatnode()
{
node *p;
p=(node *)malloc(sizeof(node));
p->next=NULL;
return p;
}
void insertnode(node * L,int x)
{
node *p;
p=(node *)malloc(sizeof(node));
p->data=x;
p->next=L->next;
L->next=p;
}
void deletenode(node * L,int x)
{
        node *p=L;
        while(p->next!=NULL&&(p->next->data!=x))
        {
                p=p->next;

        }
        if(p->next==NULL)
                cout<<"no found!!!"<<endl;
        else
        {
                p->next=p->next->next;

                cout<<"delete succuss!!!"<<endl;
        }

}
void printnode(node *L)
{
        node *p=L;
        while(p->next!=NULL)
        {
                p=p->next;
                cout<<p->data<<"  ";
        }
        cout<<endl;
}
int  searchnode(node *L, int x)//返回值为x 的位置,可以修改返回类型和返回值使其为指针
{
//头节点的位置为0、
node *p=L;
int cnt=0;
 while(p->next!=NULL&&(p->next->data!=x))
        {
                p=p->next;
                cnt++;

        }
        if(p->next==NULL)
                return -1;
return cnt;
}
void alternode (node *L,int x,int xx)//将x替换为xx
{
         node *p=L;
        while(p->next!=NULL&&(p->next->data!=x))
        {
                p=p->next;

        }
        if(p->next==NULL)
                cout<<"no found!!!"<<endl;
        else
        {
                p->next->data=xx;

                cout<<"alter succuss!!!"<<endl;
        }
}

猜你喜欢

转载自blog.csdn.net/qq_34552393/article/details/79258455