#include <stdio.h>
#include <stdlib.h>
#define OK 1
#define ERROR -1
typedef struct node
{
int data;
struct node *next;
}Node;
//初始化一个节点
Node *initnode(Node *pnode, int data)
{
pnode=(Node*)malloc(sizeof(Node));
pnode->data=data;
pnode->next=NULL;
return pnode;
}
//初始化链表
Node *initlink()
{
//创建头结点
Node *phead=(Node *)malloc(sizeof(Node));
//生命一个指针ptemp让其指向头结点,用于遍历链表
Node *ptemp=phead;
for(int i=1;i<5;i++)
{
Node *a = initnode(a, i);
ptemp->next=a;
ptemp=ptemp->next;
}
return phead;
}
//链表插入
Node *insertElem(Node *phead, int elem, int pos)
{
//创建临时结点用来遍历链表
Node *ptemp=phead;
//先找到要插入的位置上的一个结点
for(int i=1;i<pos;i++)
{
if(ptemp==NULL)
{
printf("插入位置无效\n");
return phead;
}
ptemp=ptemp->next;
}
Node *c=(Node *)malloc(sizeof(Node));
c->data=elem;
c->next=ptemp->next;
ptemp->next=c;
return phead;
}
//链表删除
Node *deleteElem(Node *phead,int pos)
{
Node *ptemp=phead;
for(int i=1;i<pos;i++)
{
if(ptemp==NULL)
{
printf("删除位置无效\n");
return phead;
}
ptemp=ptemp->next;
}
Node *c=ptemp->next;
ptemp->next=c->next;
free(c);
return phead;
}
//输出链表
void display(Node *phead)
{
Node *ptemp=phead;
while(ptemp->next)
{
ptemp=ptemp->next;
printf("%d ",ptemp->data);
}
printf("\n");
}
int main()
{
printf("初始化链表\n");
Node *phead=initlink();
display(phead);
printf("在第4位置插入元素5:\n");
phead=insertElem(phead,5,4);
display(phead);
printf("删除第三个元素:\n");
phead=deleteElem(phead,3);
display(phead);
return 0;
#include <stdlib.h>
#define OK 1
#define ERROR -1
typedef struct node
{
int data;
struct node *next;
}Node;
//初始化一个节点
Node *initnode(Node *pnode, int data)
{
pnode=(Node*)malloc(sizeof(Node));
pnode->data=data;
pnode->next=NULL;
return pnode;
}
//初始化链表
Node *initlink()
{
//创建头结点
Node *phead=(Node *)malloc(sizeof(Node));
//生命一个指针ptemp让其指向头结点,用于遍历链表
Node *ptemp=phead;
for(int i=1;i<5;i++)
{
Node *a = initnode(a, i);
ptemp->next=a;
ptemp=ptemp->next;
}
return phead;
}
//链表插入
Node *insertElem(Node *phead, int elem, int pos)
{
//创建临时结点用来遍历链表
Node *ptemp=phead;
//先找到要插入的位置上的一个结点
for(int i=1;i<pos;i++)
{
if(ptemp==NULL)
{
printf("插入位置无效\n");
return phead;
}
ptemp=ptemp->next;
}
Node *c=(Node *)malloc(sizeof(Node));
c->data=elem;
c->next=ptemp->next;
ptemp->next=c;
return phead;
}
//链表删除
Node *deleteElem(Node *phead,int pos)
{
Node *ptemp=phead;
for(int i=1;i<pos;i++)
{
if(ptemp==NULL)
{
printf("删除位置无效\n");
return phead;
}
ptemp=ptemp->next;
}
Node *c=ptemp->next;
ptemp->next=c->next;
free(c);
return phead;
}
//输出链表
void display(Node *phead)
{
Node *ptemp=phead;
while(ptemp->next)
{
ptemp=ptemp->next;
printf("%d ",ptemp->data);
}
printf("\n");
}
int main()
{
printf("初始化链表\n");
Node *phead=initlink();
display(phead);
printf("在第4位置插入元素5:\n");
phead=insertElem(phead,5,4);
display(phead);
printf("删除第三个元素:\n");
phead=deleteElem(phead,3);
display(phead);
return 0;
}