链表中元素的增加与删减

来源:互联网 发布:mysql 查询替换字符串 编辑:程序博客网 时间:2024/05/02 01:40
//Geeksun 2017.11.12
//该链表未用函数实现,见谅。
#include <stdio.h>
#include <stdlib.h>
struct node
{
    int data;
    struct node *next;
};
int main()
{
    struct node *p,*q,*t,*head,*temp;
    int n,a,i,count,count1 = 0;
    printf("请输入链表中元素的个数:");
    scanf("%d",&n);
    head = NULL;
    printf("请输入:");
    for(i = 0; i < n; i++)
    {
        scanf("%d",&a);
        p = (struct node*)malloc(sizeof(struct node));
        p->data = a;
        p->next = NULL;
        if(head == NULL)
        {
            head = p;
        }
        else
        {
            q->next = p;
        }
        q = p;
    }
    printf("本链表暂时只有插入元素与删减元素的功能\n");
    printf("插入请输入1  删减请输入2\n");
    scanf("%d",&count);
    if(count == 1)
    {
        int flag = 1;
        printf("请输入要插入的值:");
        scanf("%d",&a);
        if(head->data >= a)
        {
            p = (struct node*)malloc(sizeof(struct node));
            p->data = a;
            p->next = head;
            head = p;
            flag = 0;
        }
        if(flag)
        {
            t = head;
            while(t != NULL)
            {
                if(t->next == NULL)
                {
                    p = (struct node*)malloc(sizeof(struct node));
                    p->data = a;
                    t->next = p;
                    p->next = NULL;
                    break;
                }
                if(t->next->data >= a)
                {
                    p = (struct node*)malloc(sizeof(struct node));
                    p->data = a;
                    p->next = t->next;
                    t->next = p;
                    break;
                }
                t = t->next;
            }
        }
    }
    if(count == 2)
    {
aa:
        printf("请输入要删减的值:");
        scanf("%d",&a);
        t = head;
        while(t->next != NULL)
        {
            if(head->data == a)
            {
                head = t->next;
                count1++;
                break;
            }
            if(t->next->data == a)
            {
                t->next = t->next->next;
                count1++;
                break;
            }
            t = t->next;
        }
        if(count1 == 0)
        {
            printf("输入错误\n");
            goto aa;
        }
    }
    t = head;
    while(t!=NULL)
    {
        printf("%d ",t->data);
        t = t->next;
    }
    p = head;
    while(p != NULL)
    {
        temp = p;
        p = p->next;
        free(temp);
    }
    return 0;
}

原创粉丝点击