顺序链表

来源:互联网 发布:卡巴斯基软件怎么样 编辑:程序博客网 时间:2024/05/23 14:19

include<stdio.h>
#include<stdlib.h>

struct iNode{
    int data;
    struct iNode *next;
};

struct iNode *create()
{
    struct iNode *hp =NULL;
//head

    struct iNode *tp =NULL;
//tail

    struct iNode *cp =NULL;
//current

    int data;
    while(1)
    {
        scanf("%d",&data);
        if(data <= 0)break;
        cp =(struct iNode*)malloc(sizeof(struct iNode));
        if(cp ==NULL)
        {
            printf("OVER FLOW");
            break;
        }
        cp->data = data;
        cp->next =NULL;
        if(hp ==NULL)
        {
            hp = tp = cp;
        }else{
            tp->next = cp;
            tp = cp;
        }
    }
    printf("Create Success!/n");
    return hp;
}

void head_insert(struct iNode *head,int position,int val)
{
    struct iNode *p = head;
    struct iNode *node =NULL;
    int i = 0;
    while(p &&++i < position -1)
    {
        p = p -> next;
        
//++i;

    }
    node =(struct iNode *)malloc(sizeof(struct iNode));
    node->data = val;
    node->next = p->next;
    p->next = node;
}

void tail_insert(struct iNode *head,int position,int val)
{
    struct iNode *p = head;
    struct iNode *node =NULL;
    int i = 0;
    while(p &&++i < position)
    {
        p = p->next;
    }
    node =(struct iNode *)malloc(sizeof(struct iNode));
    node->data = val;
    node->next = p->next;
    p->next = node;
}

void del_node(struct iNode *head,int position,int val)
{
    struct iNode *p = head;
    struct iNode *d =NULL;
    int i = 0;
    while(p &&++i < position -1){
        p = p->next;
    }
    d = p->next;
    p->next = d->next;
    val = d->data;
    free(d);
}

void printl(struct iNode *head)
{
    struct iNode *p = head;
    if(p !=NULL)
    {
        do{
            printf("%d ",p->data);
            p = p->next;
        }while(p !=NULL);
    }else{
        printf("List ERROR/n");
    }
    printf("/n");
}

int main()
{
    struct iNode *list= create();
    int val = 0;
    printf("List:/n");
    printl(list);
    printf("/n/nInserted 1:/n");
    head_insert(list,5,34);
    printl(list);
    printf("/n/nDeleted:/n");
    del_node(list,5,val);
    printl(list);
    printf("Element: %d/n",val);
    printf("/n/nInserted 2:/n");
    tail_insert(list,5,32);
    printl(list);
    return 0;
}

原创粉丝点击