zoukankan      html  css  js  c++  java
  • 链表的操作-三种插入法,删除,打印

    //链表有序插入和删除最重要的是预判,就是判断下一个是否满足要求,因为如果只是判断当前,那么当你找到要操作的节点时,已经过了指向该节点的指针
    
    //删除的时候注意释放空间
    
    #include<stdio.h>
    #include<stdlib.h>
    typedef struct list
    {
     int data;
     struct list*next;
    }List;
     void insert_list_2nd(List*head,int data);//表头插入 
     void insert_list_last(List*head,int data);//表尾插入 
     void insert_list_order(List*head,int data);//有序插入 
     void delete_list(List*head,int value);//从链表中删除元素 
     void print_list(List*head);//打印链表 
    int main()
    { int i;
     List*head=(List*)malloc(sizeof(List));
     head->data=-1;
     head->next=NULL;//建立头结点
     //for(i=0;i<10;i++)
      //insert_list_2nd(head,i);
      //insert_list_last(head,i);
     for(i=9;i>=0;i--)
      insert_list_order(head,i); 
     print_list(head);
     //delete_list(head,5);
     for(i=0;i<10;i++)
      delete_list(head,i);
     print_list(head);
     
    } 
    void insert_list_2nd(List*head,int data)
    {
     List*newnode=(List*)malloc(sizeof(List));
     newnode->data=data;
     newnode->next=head->next;
     head->next=newnode;  
    }
    void insert_list_last(List*head,int data)
    { List*newnode=(List*)malloc(sizeof(List));
     newnode->data=data;
     newnode->next=NULL;
     while(head->next!=NULL)
     {
      head=head->next; 
     } 
     head->next=newnode;
    }
    void insert_list_order(List*head,int data)
    {
     List*newnode=(List*)malloc(sizeof(List));
     newnode->data=data;
     newnode->next=NULL;
     if(head->next==NULL)//链表中除了头结点没有其他结点 
     {
      head->next=newnode;
      return ;
     } 
     while(head->next && head->next->data<data)
     {
      head=head->next;
     }
    /* if(head->next==NULL)//要插入的数是最大的 
     {
      head->next=newnode; 
     }
     else//找到要插入的位置,未在最后 
     {
      newnode->next=head->next;
      head->next=newnode; 
     }*/
     newnode->next=head->next;
     head->next=newnode; 
     
    }
    void delete_list(List*head,int value)
    { List*p;
     while(head->next && head->next->data!=value)
     {
      head=head->next; 
     }  
     if(head->next==NULL)
     {
      printf("has no number of %d
    ",value);
      return ; 
     }
     p=head->next;
     head->next=head->next->next; 
     free(p);
    }
    void print_list(List*head)
    { 
     while(head)
     {
      printf("%d
    ",head->data);
      head=head->next; 
     } 
    }
  • 相关阅读:
    深入理解SQL的四种连接-左外连接、右外连接、内连接、全连接
    sql之group by的用法
    jmeter参数化
    jmeter--FTP测试
    jmeter基础概念
    开源性能测试工具——jemeter介绍+安装说明
    mysql安装图解 mysql图文安装教程(详细说明)
    Elasticsearch全文检索优化研究
    如何正确的关闭Elasticsearch集群
    自定义查询系统架构设计分析
  • 原文地址:https://www.cnblogs.com/wc1903036673/p/3499510.html
Copyright © 2011-2022 走看看