链表的插入删除和遍历

什么都不说直接上代码

#include<bits/stdc++.h>
using namespace std;
struct Student{
    int id;
    char name[16];
    Student* next;
};
Student m_head ={0};
//按顺序插入节点 
int insert(Student* obj)
{
    Student* cur = m_head.next;//当前节点current
    Student* pre = &m_head;//上一个节点previous
    while(cur)
    {
        if(obj->id<cur->id)//找到这个位置
            break;
        pre = cur;
        cur = cur->next;//找到最后一个对象 
     } 
     //插入到pre节点的后面
     obj->next = pre->next;
     pre->next = obj;
     return 0; 
}
//遍历对象 
void show_all() 
{
    Student* p = m_head.next;
    while(p)
    {
        printf("ID: %d,name:%s\n",p->id,p->name);
        p=p->next;//下一个对象 
    }
}
//按照id查找并删除节点
void remove( int id)
{
    Student* cur = m_head.next;
    Student* pre = &m_head;
    while(cur)
    {
        if(id==cur->id)
        {
            pre->next = cur->next;
            free(cur);//找到该节点并删除该节点 
            break;
        }
        pre = cur;
        cur=cur->next;//换到最后一个对象 
    }
}
int main ()
{
    Student* obj = NULL; 
    obj = (Student*)malloc(sizeof(Student));
    obj->id = 1;
    strcpy(obj->name,"111");
    insert(obj);
    
    obj = (Student*)malloc(sizeof(Student));
    obj->id = 3;
    strcpy(obj->name,"333");
    insert(obj);

    obj = (Student*)malloc(sizeof(Student));
    obj->id = 4;
    strcpy(obj->name,"444");
    insert(obj);
    remove(3); 
    show_all(); 
    return 0;
 } 

猜你喜欢

转载自www.cnblogs.com/chuxinbubian/p/10674107.html