球球同学 刚学习了单链表的建立,自己写的代码分享给大家!
包括单链表的建立,初始化,合并两个单链表,删除特定位置的元素,在特定位置加入一个元素 这些基本的操作。
代码如下:
#include <stdio.h>
#include <stdlib.h>
typedef int ElemType; //ElemType 声明为int 型;
typedef struct LNode
{
ElemType data; //数据域 ;
struct LNode *next; //指针域;
}LNode,*LinkList;
LNode *creatList(LNode *L,int n)//尾插法初始化单链表,还有头插法小伙伴们自行了解
{
LNode *p,*q;
int i,j;
L=q=p=(LinkList)malloc(sizeof(LNode));
p->next=NULL;
printf(“Data:”);
for(i=0;i<n;i++)
{
if(p!=L)
{
q->next=p;
q=q->next;
}
scanf("%d",&p->data);
p=(LinkList)malloc(sizeof(LNode));
p->next=NULL;
}
q->next=NULL;
return L;
}
LNode* MergeList(LNode *L1,LNode *L2)//合并两个单链表
{
LNode *p,*q,*s,*L,*t;
p=L1,q=L2;
s=(LinkList)malloc(sizeof(LNode));
L=t=s;
s->next=NULL;
while(p&&q)
{
if(L!=s) //不是首元素地址
{
t->next=s;
t=t->next;
}
if(p->data<=q->data)
{
s->data=p->data;
p=p->next;
}
else
{
s->data=q->data;
q=q->next;
}
s=(LinkList)malloc(sizeof(LNode));
}
while§
{
s=p;
p=p->next;
t->next=s;
t=t->next;
s=(LinkList)malloc(sizeof(LNode));
}
while(q)
{
s=q;
q=q->next;
t->next=s;
t=t->next;
s=(LinkList)malloc(sizeof(LNode));
}
t->next=NULL;
printf(“排列后的序列:\n”);
return L;//返回 合并的单链表的起始地址
}
void dele(LNode *p) //删除特定位置的元素
{
int j=1,i;
printf(“请输入删除的位置:\n”); //输入位置;
scanf("%d",&i);
while(p&&j<i-1)
{
p=p->next;
j++;
}
if(i>j+1)
{
printf(“没有这个数!\n”);
return;
}
p->next=p->next->next;
}
void insert(LNode *p)
{
int i,j;
LNode *q,*L;
ElemType e;
printf(“请输入插入的位置:\n”);
scanf("%d",&i);
printf(“请输入要插入的数:”);
scanf("%d",&e);
for(j=1;j<i;j++)
{
q=p;
p=p->next;
}
L=(LinkList)malloc(sizeof(LNode));
L->data=e;
q->next=L;
L->next=p;
}
void display(LNode *p)//展示函数
{
while§
{
printf("%d “,p->data);
p=p->next;
}
printf(”\n");
}
int main(int argc, char *argv[]) {
LNode *p,*q,*L;
p=creatList(p,4); //初始化,表长为4,可以更改为其他的数值,
q=creatList(q,4);
L=MergeList(p,q);
display(L);
dele(L); //删除函数
printf(“删去后:”);
display(L);
insert(L); //插入函数
printf(“加入后:”);
display(L);
return 0;
}
运行结果:
如果有错误,欢迎大家指正!我是球球。。