欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

结构体实现单向链表

程序员文章站 2022-04-30 19:36:19
...

结构体实现单向链表

1.定义一个结构体

 

#include<iostream>
#include<cstdlib>
using namespace std ;
#define LEN (sizeof(struct student))
struct student{

  int num ;
  float score ;
  struct student *next ;

};
//定义全局变量,记录链表中所含节点个数
int n ;

 2.创建一个链表

 

/**
创建一个链表
*/
struct student *creat(void){
    struct student*p1,*p2,*head;
    n=0 ;
    p1=(struct student*)malloc(LEN) ;
    p2 = p1 ;
    head = NULL ;
    cin>>p1->num>>p1->score ;
    while(p1->num!=0)
    {
        n = n+1 ;
      if(n==1) head = p1 ;
      else p2->next = p1 ;

      p2 = p1 ;

      p1 = (struct student*)malloc(LEN) ;
      cin>>p1->num>>p1->score ;
      }
       p2->next = NULL ;
       return head ;

}

 3.输出链表

 

/**
输出链表
*/
void print(struct student *head)
{
    struct student *p0 ;
     p0 = head ;
     while(head!=NULL)
     {
         cout<<"学号"<<p0->num<<"  分数"<<p0->score<<endl ;
         p0 = p0->next ;
         if(p0==NULL) break ;
     }
}

 4.删除节点 

/**
删除节点  
*/
struct student *del(struct student *head,long num)
{
     struct student *p1,*p2;
     p1= head ;
     while(p1->num!=num)//找到了
     {    p2 = p1 ;
         p1=p1->next ;
         if(p1==NULL)
         {
             cout<<num<<"没找到"<<endl ;
             return head ;
         }
     }
     if(p1==head) head = head->next ;
     else{ p2->next = p1->next ;}
     cout<<"已删除"<<num<<endl ;
      free(p1) ;
      n = n-1 ;
      return head ;
}

 5.插入节点    

/**
插入节点  
*/
struct student *Insert(struct student *head,struct student *stu)
{
    struct student *p1,*p2 ;
    p1 = head ;
    if(head==NULL)
    {
        head = stu ;
    stu->next = NULL ;
    }else{
    while((p1->num<stu->num)&&(p1->next!=NULL))
    {
         p2 = p1 ;
         p1 = p1->next ;
     }
     if(p1->num>stu->num)
     {
         if(p1==head) head = stu;
         else  p2->next = stu ;

         stu->next = p1 ;

     }else
     {
      p1->next = stu ;
      stu ->next = NULL ;
     }
    }
     n = n+1 ;
     cout<<"已插入"<<endl ;
     return head ;
};

 6.对链表的综合操作

  

int main()
{
    struct student *head,*stu ;
    long del_num ;
    stu =(struct student*)malloc(LEN) ;
    cout<<"请输入!!!"<<endl;
    head = creat();
    print(head) ;
    cout<<"请输入要删除的元素!!!"<<endl ;
    cin>>del_num ;
    head = del(head,del_num) ;
    print(head) ;
    cout<<"请输入要插入的元素!!!"<<endl ;
    cin>>stu->num>>stu->score ;
    head = Insert(head,stu) ;
    print(head) ;


  return 0 ;

}

 

相关标签: 结构体