这段代码实现了一个简单的学生信息管理系统,其中涉及到链表的基本操作:
- 创建链表:定义一个头节点并返回其指针。
 
Node* createList(){
    Node* head = new Node(); // 头节点不存放数据,只是起到连接作用
    head->next = nullptr; // 初始化为空链表
    return head;
}
- 插入新节点:在链表末尾插入新节点。
 
void insertNode(Node* head, Student s){
    Node* newNode = new Node(); // 新建节点
    newNode->data = s; // 将学生信息存储在新节点中
    Node* p = head;
    while(p->next != nullptr){ // 找到最后一个节点
        p = p->next;
    }
    
    p->next = newNode; // 将新节点插入到末尾
}
- 删除指定id的节点:遍历链表查找指定id的学生信息所在位置,并删除该节点。
 
bool deleteNode(Node* head, int id){
    Node* p1 = head; 
    Node* p2 = head->next;
   while(p2 != nullptr && p2->data.id != id){ // 查找指定id的学生信息所在位置
        p1 = p2;
        p2 = p2->next;
   }
   if(p2 == nullptr){
       return false; // 未找到
   }
    
   p1 -> next=p2 -> next ; // 删除节点
   delete  p2 ;
   return true; 
}
- 查找指定id的节点:遍历链表查找指定id的学生信息所在位置,并返回其节点指针。
 
Node* findNode(Node* head, int id){
    Node *p=head -> next ;  
    while (p != NULL &&p ->data.id!=id) { // 遍历链表查找
        p= 	p -> next ;  
    }   
    if (p == NULL ) {
        return NULL ; 
    }else{
        return 	p ; 
    }
}
- 统计节点个数:遍历链表并统计节点个数。
 
int countNodes(Node* head){
    int count=0;  
    Node *p=head -> next ;  
    while (p !=NULL ){
        count++;
        p=p -> next ; 
     }
     return count; 	
}
- 输出所有节点信息:遍历链表并输出每一个节点的学生信息。
 
void printList(Node* head){
	cout << "学号\t姓名\t年龄" << endl;
    Node* p = head->next;
    while(p != nullptr){ // 遍历链表并输出每一个节点的学生信息
        cout << p->data.id << "\t" << p->data.name << "\t" << p->data.age << endl;
        p = p->next;
    }
}
                                    

        
        
        
        
        
        
        
        
        
                
                
                
                
                
                
                