单链表新增删除节点操作

代码如下:

#include 
#include 

struct node
{
    int info;
    struct node *link;
};
struct node *start = NULL;

/*创建节点*/
struct node *createnode() 
{
    struct node *t;
    t = (struct node *)malloc(sizeof(struct node));
    return (t);
}

/*在链表头插入节点*/
void insert()  
{
    struct node *p;
    p = createnode();
    printf("\nenter the number to insert:");
    scanf("%d", &p->info);
    p->link = NULL;
    if (start == NULL)
    {
        start = p;
    }
    else
    {
        p->link = start;
        start = p;
    }
}

/*删除第一个节点*/
void deletion() 
{
    struct node *t;
    if (start == NULL)
    {
        printf("\nlist is empty");
    }
    else
    {
        struct node *p;
        p = start;
        start = start->link;
        free(p);
    }
}

/*显示所有节点*/
void viewlist() 
{
    struct node *p;
    if (start == NULL)
    {
        printf("\nlist is empty");
    }
    else
    {
        p = start;
        while (p != NULL)
        {
            printf("%d ", p->info);
            p = p->link;
        }
    }
}

int main()
{
    int n;
    while (1)
    {
        printf("\n1.add value at first location");
        printf("\n2.delete value from first location");
        printf("\n3.view value");
        printf("\n4.exit\n");
        printf("\nenter your choice: ");
        scanf("%d", &n);
        switch (n)
        {
        case 1:
            insert();
            break;
        case 2:
            deletion();
            break;
        case 3:
            viewlist();
            break;
        case 4:
            exit(1);
            break;
        default:
            printf("\ninvalid choice\n");
        }
    }
    return (0);
}

运行结果:

1.add value at first location
2.delete value from first location
3.view value
4.exit

enter your choice: 2

list is empty
1.add value at first location
2.delete value from first location
3.view value
4.exit

enter your choice: 1

enter the number to insert:90

1.add value at first location
2.delete value from first location
3.view value
4.exit

enter your choice: 1

enter the number to insert:66

1.add value at first location
2.delete value from first location
3.view value
4.exit

enter your choice: 1

enter the number to insert:33

1.add value at first location
2.delete value from first location
3.view value
4.exit

enter your choice: 3
33 66 90 
1.add value at first location
2.delete value from first location
3.view value
4.exit

enter your choice: 2

1.add value at first location
2.delete value from first location
3.view value
4.exit

enter your choice: 66

invalid choice

1.add value at first location
2.delete value from first location
3.view value
4.exit

enter your choice: 3
66 90 
1.add value at first location
2.delete value from first location
3.view value
4.exit

enter your choice: 4
 

 

你可能感兴趣的:(数据结构和算法,数据结构)