c语言链表

c语言链表,第1张

 1.链表由一系列结点(链表中每一个元素称为结点)组成,结点可以在运行时动态生成。每个结点包括两个部分:一个是存储数据元素的数据域,另一个是存储下一个结点地址的指针域

2.使用链表结构可以克服数组需要预先知道数据大小的缺点,链表结构可以充分利用计算机内存空间,实现灵活的内存动态管理。但是链表失去了数组随机读取的优点,同时链表由于增加了结点的指针域,空间开销比较大。

3.链表允许插入和移除表上任意位置上的节点,但是不允许随机存取

#include 
#include 
/*结构体创建*/
typedef struct _node{
  int value;
  struct _node* next;

}Node;



Node* add(Node* head,int number);
void print(Node* head);

int main()
{
    Node* head=NULL;
   int number;
   printf("输入数创建链表");
   do{
    scanf("%d",&number);
    if(number!=-1){
        head=add(head,number);//add函数为链表连接函数,在main函数下方
   }
   }
   while(number!=-1);
    print(head);



    printf("输入想找的数");
    scanf("%d",&number);
    Node* p;
    int isfound=0;
    for(p=head;p;p=p->next)
    {
       if(p->value==number)
       {
           printf("找到了\n");
           isfound=1;
           break;
       }


    }
    printf("删掉链表元素");
    int number2;
    scanf("%d",number2);
    Node* q;
    for(q=NULL,p=head;p;q=p,p=p->next)
    {
       if(p->value==number2)
       {   if(q){
           q->next=p->next;}
           else{

            head=p->next;
           }
           free(p);
           break;

       }
}

print(head);


    /*整个链表删除*/
    printf("删除链表");


    for(p=head;p;p=q)
    {
        q=p->next;
        free(p);
    }


    return 0;
}
/*链表连接*/

Node* add(Node* head,int number)
{
 //add to linked-list
        Node* p=(Node*)malloc(sizeof(Node));
        p->value=number;
        p->next=NULL;
        Node* last=head;
        if(last){
        while(last->next)
        {
            last=last->next;
        }
        last->next=p;
        }
        else {
            head=p;
        }

        return head;
}

void print(Node* head)
{

/*输出*/
Node* p;
   for(p=head;p;p=p->next)
   {
       printf("%d\t",p->value);
   }
   printf("\n");
}

欢迎分享,转载请注明来源:内存溢出

原文地址: https://outofmemory.cn/langs/874001.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-05-13
下一篇 2022-05-13

发表评论

登录后才能评论

评论列表(0条)

保存