单链表的简单操作

#include<stdio.h>
#include<ctype.h>
#include<stdlib.h>
#define OK 1
#define ERROR 0

typedef int Status;

typedef struct Lnode
{
    int data;
    struct Lnode *next;
}Lnode, *Linklist;

int m = sizeof(Lnode);

Linklist CreateList(int n)
{
    Linklist s, L;
    L = (Linklist)malloc(m);
    L->next = NULL;
    while(n--)
    {
        s = (Linklist)malloc(m);
        scanf("%d", &s->data);
        s->next = L->next;
        L->next = s;
    }
    return L;
}

void TraverseList(Linklist L)
{
    Linklist p = L->next;
    while(p)
    {
        printf("%d ", p->data);
        p = p->next;
    }
    printf("\n");
}

Status ListInsert(Linklist L, int i, int e)
{
    int j = 1;
    Linklist p, s, s1;
    p = L;
    s = L->next;
    while(s && j < i)
    {
        p = s;
        s = s->next;
        j++;
    }
    if((s == NULL && j < i) || i < 1)
        return ERROR;
    s1 = (Linklist)malloc(m);
    s1->data = e;
    s1->next = p->next;
    p->next = s1;
    return OK;
}


Status ListDel(Linklist L, int i)
{
    Linklist p = L, s = L->next;
    int j = 1;
    while(s && j < i)
    {
        p = s;
        s = s->next;
        j++;
    }
    if((s == NULL && j < i) || i < 1)
        return ERROR;
    p->next = s->next;
    free(s);
    return OK;
}

int main()
{
    int n, k, x, y;
    Linklist L;
    scanf("%d", &n);
    L = CreateList(n);
    printf("生成的数组是:\n");
    TraverseList(L);
    scanf("%d", &k);
    ListDel(L, k);
    printf("删除后得到:\n");
    TraverseList(L);
    scanf("%d%d", &x, &y);
    ListInsert(L, x, y);
    printf("插入后得到:\n");
    TraverseList(L);
    return 0;
}

 

posted @ 2015-10-09 15:51  午夜阳光~  阅读(118)  评论(0编辑  收藏  举报