初始化链表
#include<string.h> #include<stdio.h> #include<stdlib.h> typedef struct node{ char name[20]; double score; struct node* next; }Node; //初始化头节点,并返回头指针 Node* list_init() { Node* head = (Node*)malloc(sizeof(Node)); //查看空间是否开辟 if(head==NULL) { return NULL; } //头节点可以不放数据 strcpy(head->name,"acs"); head->score=0.0; head->next=NULL; return head; //创建了一个节点,并且head指向它,这个节点指向空 }
头插法
//头插法,插入节点 void head_insert(Node* head,char* p,double s) { Node* new_node = (Node*)malloc(sizeof(Node)); strcpy(new_node->name,p); new_node->score=s; new_node->next=NULL; new_node->next = head->next; head->next = new_node; }
尾插法
//尾插法,插入节点 void tail_insert(Node* head,char* p,double s) { Node* new_node = (Node*)malloc(sizeof(Node)); Node* pp = head; strcpy(new_node->name,p); new_node->score=s; new_node->next=NULL; while(pp->next!=NULL) { pp=pp->next; } pp->next = new_node; }
遍历并打印
//实现打印功能 void print_list(Node* head) { Node* p = head; while(p->next!=NULL) { p=p->next; printf("%s %f\n",p->name,p->score); } }
计算链表节点数
//计算链表中有多少个节点 int node_num(Node* head) { Node* p = head; int count=0; while(p!=NULL) { p=p->next; count++; } return count; }
主函数的调用
int main() { Node* head=list_init(); head_insert(head,"张三",88.5); head_insert(head,"李四",99.0); head_insert(head,"王五",80.0); head_insert(head,"长空",100.5); head_insert(head,"小凡",60.4); tail_insert(head,"天了",88.4); tail_insert(head,"小白",78.9); print_list(head); int num = node_num(head); printf("一共有%d个节点\n",num); return 0; }