單鏈表(線性鏈表)的建立與基礎

球球同學 剛學習了單鏈表的建立,自己寫的代碼分享給大家!
包括單鏈表的建立初始化合併兩個單鏈表,刪除特定位置的元素,在特定位置加入一個元素 這些基本的操作。
代碼如下:
#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;
}
運行結果:
在這裏插入圖片描述
如果有錯誤,歡迎大家指正!我是球球。。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章