学计算机的同鞋们都知道,我们伟大的数据结构中有个东西叫单链表,这东西跟单恋似的,苦中带甜,甜中微苦。
下面我们就拉一拉单链表的建立、插入和删除。咱们不整那些虚的,我也是刚开始写,如有错误,希望各位大佬斧正指出。
本片使用尾插法进行操作
- 建立
在一切开始之前,我们先来个初始化,把未知的东西声明一下,我们所学的C#、Java均是如此,原理不一,此处只是类比推理,方便理解。
初始化:申请头节点
first=malloc(size);//malloc(size)函数申请节点空间
rear=first;
再依次插入元素节点
先申请空间
再存数据
再将rear向后移
只要是持续增加元素节点,这四步是不用变的
s=malloc(size);
s->data=x;//x是所需存入的数据
rear->next=s;
rear->=s;
循环结束将最后一个指针域指向NULL
rear->next=NULL;
- 插入
转换一下指针指向
申请节点空间s,再将数据x赋给s的数据域,
再将1指针变成2,即将p->next赋给s->next,
再让改变后的p->next指向s
s=malloc(size);
s->sata=x;
s->next=p->next;
p->next=s;
- 删除
q=p->next;
x=q->data;
p->next=q->next;
free q;
整体运行实验代码
#include "stdio.h"
#include "stdlib.h"
typedef struct ss
{ int data;
struct ss *next;
}LNode;
LNode *Creat()
{
LNode *h,*p,*q;
int x;
h=(LNode *)malloc(sizeof(LNode));
h->next=NULL;
q=h;
scanf("%d",&x);
while(x!=-1)
{ p=(LNode *)malloc(sizeof(LNode));
p->data=x;
p->next=NULL;
q->next=p;
q=p;
scanf("%d",&x);
}
return h;
}
void Out(LNode *h)
{ LNode *p;
p=h->next;
if(p==NULL)
{ printf("空表!\n");
return;
}
while(p!=NULL){
printf("%d",p->data);
p=p->next;
}
}
void InsertList(LNode *h,int i,int e)
{
LNode *s,*p;
int j=1;
p=h->next;
while(p&&j<i-1)
{
p=p->next;
++j;
}
s=(LNode *)malloc(sizeof(LNode));
s->data=e;
s->next=p->next;
p->next=s;
}
void DelList(LNode *h,int i)
{
LNode *p,*q;
int j=1;
int e;
p=h->next;
while(p&&j<i-1)
{
p=p->next;
j++;
}
q=p->next;
e=q->data;
if(q->next!=NULL)
p->next=q->next;
else
p->next=NULL;
free(q);
printf("\n删除元素为:%d",e);
}
void main()
{ printf("请输入链表数,每输一个,enter一下,‘-1’结束\n");
LNode *head;
int i,x;
head=Creat();
Out(head);
printf("\n请输入插入位置(输入-1结束):");
scanf("%d",&i);
printf("请输入插入数据:");
scanf("%d",&x);
InsertList(head,i,x);
printf("插入后单链表为:\n");
Out(head);
printf("\n请输入删除位置:");
scanf("%d",&i);
DelList(head,i);
printf("\n删除后单链表为:\n");
Out(head);
}
随意输出结果展示