C链表操作

C链表操作


#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;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值