依睛(IT blog) 我回来了,PHP<-->C/C++ LINUX

笨鸟

统计

积分与排名

友情连接

最新评论

C链表操作


标一下转的. 别人心心苦苦写的.
C链表操作
复习数据结构和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;
}

posted on 2008-10-29 14:24 向左向右走 阅读(2324) 评论(2)  编辑 收藏 引用 所属分类: C/C++学习资料库

评论

# re: C链表操作 2009-10-10 17:44 绿叶

tail_insert 写错了。  回复  更多评论   

# re: C链表操作 2009-10-12 13:35 cohan

有问题吧,create函数中hp->next一直是NULL  回复  更多评论   

只有注册用户登录后才能发表评论。