创建一个链表,插入删除,指定元素

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/wwwww_bw/article/details/53386108
#include <stdio.h>
#include <malloc.h>
typedef struct Node
{
    int num;
    struct Node* next;
}node;
void create(node*head)
{
    node *p;
    int i;
    int a;
    int len1;
    printf("please input length:");
    scanf("%d",&len1);
    printf("please input number:\n");
    for(i = 0;i < len1;i++)
    {
        scanf("%d",&a);
        p = (node*)malloc(sizeof(node));
        p->num = a;
        p->next = head->next;
        head->next = p;
    }
}
void del_num(node *head,int i)
{
    node *p;
    node *q;
    q = head;
    p = q->next;
   
    while((p != NULL) && (p->num != i))
    {
        q = p;
        p = p->next;
    }
    if( p == NULL)
    {
        printf("not find");
    }
    else
    {
        q->next = p->next;
        free(p);
    }
}
void print(node*head)
{
    node *p;
    p = head->next;
    printf("num:");
    while(p)
    {
        printf("%4d",p->num);
        p = p->next;
    }
    printf("\n");
}
void add_num(node*head,int j,int k)
{
    node*p;
    p = (node*)malloc(sizeof(node));
   
    if(j <= 0)
    {
        printf("        \nerror\n       ");
    }
    else
    {
        while(j > 1)
        {
            head = head->next;
            j--;
        }
        p->num = k;
        p->next = head->next;
        head->next = p;
    }
}
int main()
{
    node *a;
    node *b;
    node *head;
    int i;
    int j;
    int k;
    head = (node*)malloc(sizeof(node));
    head->next = NULL;
    a = head;
    create(a);
    print(a);
   
    printf("please input delet: ");
    scanf("%d",&i);
    del_num(a,i);
    print(a);
    printf("please input place:");
    scanf("%d",&j);
    printf("please input number:");
    scanf("%d",&k);
    add_num(a,j,k);
    print(a);
}

猜你喜欢

转载自blog.csdn.net/wwwww_bw/article/details/53386108
今日推荐