c语言单链表课件,单链表(C语言)

#include #include

//结构体实现自定义

typedef structLNode{int elem;//代表数据域

struct LNode *next;//代表指针域,指向直接后继元素

}LNode, LinkList;//初始化链表//LNode * initLink();

LNode *initLink(){

LinkList* p = (LinkList*)malloc(sizeof(LNode));

LNode* temp = p; //声明一个指针指向头结点//生成链表

for(int i = 1; i < 5; i++){

LNode*a = (LNode*)malloc(sizeof(LNode));

a->elem =i;

a->next =NULL;

temp->next =a;

temp= temp->next;

}returnp;

}//*******************************************************//************插入函数***********************************//p是链表,elem是插入的结点的数据域,add是插入的位置

LNode * insertElem(LNode * p, int elem, intadd){

LNode* temp = p; //创建临时结点temp//首先找到要插入位置的上一个结点

for(int i = 1; i < add; i++) {if(temp ==NULL){

printf("插入位置无效");returnp;

}

temp= temp->next;

}//创建插入结点c

LNode * c = (LNode *)malloc(sizeof(LNode));

c->elem =elem;//向链表中插入结点

c->next = temp->next;

temp->next =c;returnp;

}//*******************************************************//************删除函数***********************************

LNode * delElem(LNode * p, intadd){

LNode* temp =p;//遍历到被删除结点的上一个结点

for(int i = 1; i < add; i++){

temp= temp->next;

}

LNode* del = temp->next;//单独设置一个指针指向被删除的结点//删除某个结点的方法就是更改前一个结点的指针域

temp->next = temp->next->next;free(del);//手动释放该结点,防止内存泄漏

returnp;

}//*******************************************************//************查找函数***********************************

int selectElem(LNode * p, intelem){

LNode* t =p;int i = 1;while(t->next){

t= t->next;if(t->elem ==elem){returni;

}

i++;

}return -1;

}//*******************************************************//************更改函数***********************************

LNode * updateElem(LNode * p, int add, intnewElem){

LNode* temp =p;

temp= temp->next;//temp指向首源结点//temp指向被删除的结点

for(int i = 1; i < add; i++){

temp= temp->next;

}

temp->elem =newElem;returnp;

}//void display(LNode *p);

void display(LNode *p){

LNode* temp = p; //将temp指针重新指向头结点//只要temp指针指向的结点的next不是Null,就执行输出语句

while(temp->next){

temp= temp->next;

printf("%d",temp->elem);

}

printf("");

}intmain(){

printf("初始化链表为:");

LinkList*p =initLink();

display(p);//插入函数

printf("在第四个位置插入元素5:");

p= insertElem(p, 5, 4);

display(p);//删除操作

printf("删除元素3:");

p= delElem(p, 3);

display(p);//查找操作

printf("查找元素2:");int address = selectElem(p, 2);if(address == -1){

printf("没有查到该元素");

}else{

printf("元素2的位置在:%d", address);

}//更改操作,将第三的位置改为数字999

printf("更改第三的位置数据为999:");

p= updateElem(p, 3, 999);

display(p);return 0;

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值