C语言之单链表
一、学习要点:
1.指针在使用的时候一定要初始化;
初始化原因不明白见我博客:
https://blog.****.net/fyf18845165207/article/details/82954228
2.注意动态分配和释放内存的函数malloc和delete;
二、程序代码:
#include<stdlib.h>
#include<stdio.h>
#include<malloc.h>
typedef int ElemType;
typedef struct Node{
ElemType data;
struct Node *next;
}Node,*list;
list create_head();//确定链表头结点
void create_list(list head,int n);//创造长度为n的单链表
void print(list head);//打印单链表
void delete_list(list head,int pos);//删除单链表元素
list create_head(){
list p;
p=(list)malloc(sizeof(Node));
if(p==NULL){
printf("内存分配失败");
}else{
p->next=NULL;
return(p);
}
}
void create_list(list head,int n){
list p,temp;
ElemType ch;
p=head;
while(n--){
scanf("%d",&ch);
temp=(list)malloc(sizeof(Node));
temp->data=ch;
temp->next=p->next;
p->next=temp;
p=temp;
}
}
void print_list(list head){
list p;
p=head->next;//第一个节点
while(p!=NULL){
printf("%d\n",p->data);
p=p->next;
}
}
void delete_list(list head,int pos){
list p;
list temp;
p=head;
for(int i=1;i<pos;i++){
p=p->next;
}
temp=(list)malloc(sizeof(Node));
temp=p->next;
p->next=p->next->next;
delete temp;
}
int main(){//主函数
Node *head;
head=create_head();
create_list(head,5);
printf("打印创建的单链表:\n");
print_list(head);
delete_list(head,3);
printf("打印删除第三个节点后的单链表:\n");
print_list(head);
system("pause");
return 0;
}
三、程序运行结果: