链表定义
typedef struct LinkList{
char name[12];
int age;
char gender;
struct LinkList* next;
}LinkList;
链表的测试
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct LinkList{
char name[12];
int age;
char gender;
struct LinkList* next;
}LinkList;
int main(){
LinkList* head = NULL;
LinkList* current = NULL;
head = (LinkList*)malloc(sizeof(LinkList));
head->next = NULL;
LinkList* node = (LinkList*)malloc(sizeof(LinkList));
// char ptr[5] = {'j','e','f','f','\n'};
char* ptr = "jeffxu";
memcpy(node->name,ptr,sizeof(ptr));
node->age = 25;
node->gender = 'M';
node->next = NULL;
head->next = node;
current = node;
printf("%s\n",current->name);
LinkList* node1 = (LinkList*)malloc(sizeof(LinkList));
// char ptr[5] = {'j','e','f','f','\n'};
char* ptr1 = "bobo";
memcpy(node1->name,ptr1,sizeof(ptr1));
node1->age = 24;
node1->gender = 'W';
node1->next = NULL;
current->next = node1;
current = node1;
printf("%s\n",current->name);
LinkList* node2 = (LinkList*)malloc(sizeof(LinkList));
// char ptr[5] = {'j','e','f','f','\n'};
char* ptr2 = "candy";
memcpy(node2->name,ptr2,sizeof(ptr2));
node2->age = 20;
node2->gender = 'W';
node2->next = NULL;
current->next = node2;
current = node2;
printf("%s\n",current->name);
LinkList* tmp = head;
for(;tmp->next != NULL;){
tmp = tmp->next;
printf("%s\n",tmp->name);
}
printf("123");
return 0;
}
输出
jeffxu
bobo
candy
jeffxu
bobo
candy
123
总结
这里的链表实现采用了有头结点的方式,然后使用current指针一直指向新插入的结点,这样后续既可以持续插入新结点(这里采用的是尾插法),也可以从头遍历整个链表。