单链表的定义
由于顺序表的插入删除操作需要移动大量的元素,影响了运行效率,因此引入了线性表的链式存储——单链表。单链表通过一组任意的存储单元来存储线性表中的数据元素,不需要使用地址连续的存储单元,因此它不要求在逻辑上相邻的两个元素在物理位置上也相邻。
#include <stdio.h> #include <stdlib.h> struct stu{ int num; struct stu* next; }; //创建一个头结点 struct stu* creat_list(){ struct stu *headNode=(struct stu*) malloc(sizeof(struct stu)); // headNode->num=0; headNode->next=NULL; return headNode; } //创建一个结点 struct stu *creat_node(int num){ struct stu *node=(struct stu*) malloc(sizeof(struct stu)); node->num=num; node->next=NULL; return node; } //创建一个单链表,头插法 void insert_byHead(struct stu *headNode,int num){ struct stu* newnode=creat_node(num); newnode->next= headNode->next; headNode->next=newnode; } //尾插法 void insert_tail(struct stu *List,int num){ while(List->next) List = List->next; struct stu *h=List; struct stu *newnode= creat_node(num); h->next=newnode; h=newnode; newnode->next=NULL; } void printList(struct stu* headNode){ struct stu *pmove=headNode->next; while (pmove){ printf("%d ",pmove->num); pmove=pmove->next; } printf("\n"); } void delete(struct stu *list,int num){ struct stu* pos=list->next; struct stu* posfront=list; if(posfront->next==NULL){ printf("the link is empty\n"); } else{ while (pos->num!=num){ posfront=pos; pos=pos->next; } if(pos->next==NULL){ printf("Not find"); } } posfront->next=pos->next; free(pos); } void main(){ struct stu *list=creat_list(); insert_byHead(list,222); insert_byHead(list,111); insert_byHead(list,555); insert_byHead(list,33); insert_tail(list,666); insert_byHead(list,9); insert_tail(list,0); printList(list); // delete(list,33); // printList(list); }