C语言编写一个链表
本文实例为大家分享了C语言编写一个链表的具体代码,供大家参考,具体内容如下
链表
具备的基本功能:
1.创建头链表
struct Node* Creatlist(){//创建链表头 struct Node *headnode = (struct Node*)malloc(sizeof(struct Node));//创建动态内存链表,指针变量 headnode->next = NULL;//链表初始化 return headnode; }
2.创建节点
struct Node* Creatnode(int num){//创建结点,链表,参数数字域 struct Node* newnode = (struct Node*)malloc(sizeof(struct Node));//创建动态内存链表,指针变量 newnode->num = num; newnode->next = NULL;//链表初始化 return newnode; }
3.插入节点
void Insetlist(struct Node* list, int num){//头插法 struct Node* insetnode = Creatnode(num); if (list != NULL){ insetnode->next = list->next; list->next = insetnode; } else{ printf("节点不存在\n"); } } void Insetlists(struct Node* headnode, int n, int num){//在n节点处插入,参数头节点,在第n个节点处插,插入的数据num int i = 1; struct Node *t = headnode; while (i < n&& t!= NULL){ t = t->next; i++; } if (t != NULL){ struct Node* insetnode = Creatnode(num); insetnode->next = t->next; t->next = insetnode; } else{ printf("节点不存在\n"); } }
4.修改节点
void Modifynode(struct Node* headnode, int n){//修改节点,参数链表,修改的第n个节点 struct Node* list = headnode; int i = 0; while (i < n&&list != NULL){ list = list->next; i++; } if (list != NULL){ printf("请输入你要修改的值\n"); int j = 0; scanf("%d", &j); list->num = j; } else{ printf("节点不存在\n"); } }
5.删除节点
定义两个指针,一个指向删除节点的上一个节点,一个指向要删除的节点
void Deletnode(struct Node* headnode, int n){//删除第n个节点, int i = 1; struct Node *strat = headnode; struct Node *end = headnode->next; while (i < n&&end != NULL){ strat = strat->next; end = end->next; i++; } if (end != NULL){ strat->next = end->next; free(end); } else{ printf("节点不存在\n"); } }
6.打印节点
void Printnode(struct Node* headnode){//打印节点 struct Node* list = headnode; while ((list->next) != NULL){ list = list->next; printf("%d\t", list->num); } printf("\n"); }
7.主函数
int main(){ struct Node* list = Creatlist(); Insetlists(list, 1, 1); Printnode(list); int i = 0; printf("请输入修改哪个节点\n"); scanf("%d", &i); Modifynode(list, i); Printnode(list); printf("请输入删除哪个节点\n"); int n = 0; scanf("%d", &n); Deletnode(list, n); Printnode(list); system("pause"); return 0; }
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持我们。
赞 (0)