zoukankan      html  css  js  c++  java
  • 7.5_链表_删除指定数据域的结点

    将链表中值为x的结点删除。
    #include <stdio.h>
    #include <stdlib.h>
    //将链表中值为x的结点删除
    
    //结点
    struct linkNode{
        int data;
        struct linkNode *next;
    };
    
    void output(struct linkNode *head);                         //打印链表数据域
    
    struct linkNode *creat_link_list_rear(int *a, int n);       //尾插法
    
    struct linkNode *delete_node(struct linkNode *h, int x);    //删除指定值的结点
    
    int main() {
    
        int a[6];               //存放结点数据
        int x;                  //待删除数据
        struct linkNode *head;  //头指针(尾插法)
    
        printf("输入数组各元素的值【6个】:
    ");
        for(int i=0; i<6; i++){
            scanf("%d", &a[i]);
        }
    
        head = creat_link_list_rear(a, 6);     //尾插法
    
        printf("此链表各个节点的数据为:
    ");
        output(head);
    
        printf("输入要删除的数据:
    ");
        scanf("%d", &x);
    
        head = delete_node(head, x);
    
        printf("
    此链表各个节点的数据为:
    ");
        output(head);
    
        return 0;
    }
    
    
    //尾插法
    struct linkNode *creat_link_list_rear(int a[], int n){
    
        struct linkNode *h = NULL;  //新建链表h,将每个结点依次插入到链尾,将链表的头指针返回
        struct linkNode *s;         //要插入的结点
        struct linkNode *r;         //尾结点
    
        for(int i=0; i<n; i++){
            s = (struct linkNode *)malloc(sizeof(struct linkNode));
            s->data = a[i];
            s->next = NULL;
    
            if(h == NULL){
                h = s;
            }else{
                r->next = s;
            }
    
            r = s;  //r指向当前链表的尾结点
        }
    
        return h;   //返回链表头指针
    }
    
    //删除指定值的结点
    struct linkNode *delete_node(struct linkNode *h, int x){
        struct linkNode *p;     //游标
        struct linkNode *pre;   //p的前驱
    
        p = h;
    
        while (p && x != p->data){
            pre = p;
            p = p->next;
        }
    
        if (p){     //p非空(找到了要删除的结点)
            if (p == h){    //删除节点在链首
                h = p->next;
            }else{          //删除节点在链中
                pre->next = p->next;
            }
        }
    
        return h;
    }
    
    //打印链表数据
    void output(struct linkNode *head){
        struct linkNode *p = head;
    
        while (p){
            printf("%d ", p->data);
            p = p->next;
        }
    
        printf("
    ");
    }

  • 相关阅读:
    [转]实现财务自由的6大步骤
    [转] js 实现table每列可左右拖动改变列宽度
    [转]在Excel中使用SQL语句实现精确查询
    [书目20150727]有效沟通-余世维
    [书目20150727]选择重于一切(扎克伯格给年轻人的37个人生忠告)
    [转]把汉字写“绝”了
    [转]《间架结构92法》
    深圳社保转入
    广州社保转出
    [转]利用telnet进行SMTP的验证
  • 原文地址:https://www.cnblogs.com/CPU-Easy/p/14053500.html
Copyright © 2011-2022 走看看