(一)单链表
int main(){
struct Node* list=createList();
insertNodeByHead(list,1);
insertNodeByHead(list,2);
insertNodeByHead(list,3);
printList(list);
deleteNodeByAppoin(list,2);
printList(list);
return 0;
}
一.定义
struct Node{
int data;//数据域
struct Node* next;//指针域
};
二.创建链表
struct Node* createList(){
struct Node* headNode=(struct Node*)malloc(sizeof(struct Node));
//headNode成为了结构体变量
//变量使用前必须被初始化
headNode->next=NULL;
return headNode;
}
三.创建节点
struct Node* createNode(int data){
struct Node* newNode=(struct Node*)malloc(sizeof(struct Node));
newNode->data=data;
newNode->next=NULL;
return newNode;
}
四.打印节点
void printList(struct Node* headNode){
struct Node* pMove=headNode->next;
//从第二个节点开始打印(头节点一般为空)
while(pMove){
printf("%d\t",pMove->data);
pMove=pMove->next;
}
}
五.插入节点
void insertNodeByHead(struct Node* headNode,int data){
//头插
struct Node* newNode=createNode(data);
newNode->next=headNode->next;
headNode->next=newNode;
}
六.删除节点
void deleteNodeByAppoin(struct Node* headNode,int posData){
struct Node* posNode=headNode->next;
struct Node* posNodeFront=headNode;
if(posNode==NULL)
printf("无法删除链表为空\n");
else{
while(posNode->data!=posData){
posNodeFront=posNode;
posNode=posNodeFront->next;
if(posNode==NULL){
printf("无法找到相关信息\n")
break;
}
}
posNodeFront->next=posNode->next;
free(posNode);
}
七.例:建立一个简单的学生信息储存
//不要把数据的结构体写入链表的结构体内
struct student{
char name[20];//名字
int math;//数学成绩
int num;//编号
}
struct Node{
struct student data; //数据域
struct Node* next; //指针域
}
void insertNodeByHead(struct Node* headNode,struct student data)//添加节点
void deleteNodeByAppoin(struct Node* headNode,int num)//删除指定节点(num)
{
...
while(posNode->data.num!=num)
...
}