Chinaunix首页 | 论坛 | 博客
  • 博客访问: 375895
  • 博文数量: 62
  • 博客积分: 0
  • 博客等级: 民兵
  • 技术积分: 557
  • 用 户 组: 普通用户
  • 注册时间: 2013-08-01 14:04
文章分类

全部博文(62)

文章存档

2014年(1)

2013年(61)

分类: C/C++

2013-11-17 19:36:40

原文地址:单链表的操作实现 作者:1jjk

实现了一下单链表的操作,创建,插入,删除,查找,求长度,代码写得简陋,有缺陷。一直没有好好的学习数据结构,正在一点一点的实现。
 

/*
name: list
written by: 1jjk
*/

#include<stdio.h>
#include<stdlib.h>
/*包含的文件*/

/*声明一个结构体并定义*/
typedef struct node
{
    int data;
    struct node *next;
}*pointer,*klist;

/*声明求表长*/
int lengthlist(klist list);

/*实现建立链表,这里的名写错了,呵呵*/
struct node *insert_list()
{
    klist q,d,list;
    int x;
    d=malloc(sizeof(struct node));
    list=d;
    scanf("%d", &x);
    while(x!=0)    
    {
        q=malloc(sizeof(struct node));
        list->data=x;
        list->next=q;
        list=q;
        scanf("%d", &x);    
    }
    list->next=NULL;
    return d;
}

/*get the length of the list*/
int lengthlist(klist head)
{
    klist p;
    int j=0;
    p=head;
    printf("\nout is:\n");
    while(p->next!=NULL)
    {
        printf("%d\n",p->data);
        p=p->next;
        j++;
    }
    printf("\n");
    return j;
}

/*search the node of the list*/
struct node *search_list(klist list,int i)
{
    klist p=list;
    int j=0;
    while((p->next!=NULL)&&(j<i))
    {
        p=p->next;
        j++;
    }
    if(i==j)
    {
    //    printf("%d\n",p->data);

        return p;
    }
    else
    {
        return NULL;
    }
}

/*insert one number into a node of the list*/
struct node *into_list(klist list,int num,int i)
{
    klist p,q,d;
    int j=0;
    p=list;
    d=list;
    if((search_list(list,i))==NULL)
    {
        printf("insert error\n");
        return d;
    }
    while((p->next!=NULL)&&(j<i))
    {
        p=p->next;
        j++;
    }
    if(j==i)
    {
        q=malloc(sizeof(struct node));
        q->data=num;
        q->next=p->next;
        p->next=q;
        return d;
    }
    else
    {
        return d;
    }
}

/*delete the number of the list*/
int delete_list(klist list,int i)
{
    klist p,q;
    int j=0;
    p=list;
    if((search_list(list,i))==NULL)
    {
        printf("delete error\n");
        return 0;
    }
    while((p->next!=NULL)&&(j<i))
    {
        p=p->next;
        j++;
    }
    if(j==i)
    {
        q=p->next;
        p->next=q->next;
        free(q);
        return 1;
    }
    else
    {
        return 0;
    }
}
    
    
int main()
{
    klist p;
    int i;
    p=insert_list();
    printf("%d\n",lengthlist(p));
    printf("please input which node do you want to insert a number:\n");
    scanf("%d",&i);
    search_list(p,i);
    p=into_list(p,2222,i);
    lengthlist(p);
    printf("please input which node do you want to delete:\n");
    scanf("%d",&i);
    delete_list(p,i);
    return lengthlist(p);
}

阅读(1515) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~