链表的基本操作

/*
 *@author ?
 *@since 2011/07/29
 *@function 实现链表的常用操作,比较粗糙。
 *          功能大概是:显示链表结构;查询链表;删除节点;插入结点;修改结点
 */
#include <stdio.h>
#include <stdlib.h>

struct node
{
    int value;
    struct node *next;
};
/*
 *插入结点(单个)
 */
struct node *add_to_list(struct node *list,int n)
{
    struct node *new_node;

    new_node=(node *)malloc(sizeof(struct node));
    if(new_node==NULL)
    {
        printf("Error:malloc failed in add_to_list\n");
        exit(EXIT_FAILURE);
    }
    new_node->value=n;
    new_node->next=list;

    return new_node;
}
/*
 *添加结点(多个)
 */
struct node *read_numbers(void)
{
    struct node *first=NULL;
    int n;

    printf("Enter a series of integers (0 to terminate): ");
    for(;;)
    {
        scanf("%d",&n);
        if(n==0)
        {
            return first;
        }
        first=add_to_list(first,n);
    }
}
/*
 *搜索结点
 */
struct node *search_list(struct node *list,int n)
{
    struct node *p;

    for(p=list;p!=NULL;p=p->next)
        if(p->value==n)
            return p;

    return NULL;
}
/*
 *删除结点
 */
struct node *delete_node(struct node *list,int n)
{
    struct node *cur,*prev;

    for(cur=list,prev=NULL;
        cur!=NULL&&cur->value!=n;
        prev=cur,cur=cur->next)
    ;
    if(cur==NULL)
    {
        return list;
    }
    if(prev==NULL)
    {
        list=list->next;
    }else
    {
        prev->next=cur->next;
    }
    free(cur);

    return list;
}
/*
 *修改结点
 */
struct node *update_node(struct node *list,int n)
{
    struct node *cur;
    int new_value;

    for(cur=list;cur!=NULL&&cur->value!=n;cur=cur->next)
    ;
    if(cur==NULL)
    {
        printf("NO NODE!!!");
    }
    printf("please enter the new value: ");
    scanf("%d",&new_value);
    cur->value=new_value;

    return list;
}
/*
 *打印链表结点结构
 */
void print(struct node *list)
{
    struct node *p;

    printf("The current relation of the list is ");

    for(p=list;p!=NULL;p=p->next)
    {
        if(p->next!=NULL)
        {
            printf("%d->",p->value);
        }else
        {
            printf("%d\n",p->value);
        }
    }
}

int main()
{
    struct node *test,*p;
    int n; 

    test=read_numbers();

    /*
     *输出当前链表
     */
    print(test);

    /*
     *查找链表中结点,并输出结点的值
     */
    printf("Please enter the value to look for: ");
    scanf("%d",&n);
    p=search_list(test,n);
    printf("The value of the node is %d\n",p->value);

    /*
     *删除结点并显示更新后链表的结构
     */
    printf("Please choose the value of the node you would like to delete: ");
    scanf("%d",&n);
    p=delete_node(test,n);
    print(p);

    /*
     *修改结点并显示更新后链表的结构
     */
    printf("Please choose the value of the node you would like to update: ");
    scanf("%d",&n);
    p=update_node(test,n);
    print(p);

    return 0;
}

 

posted @ 2013-09-05 22:48  cheshulin  阅读(184)  评论(0编辑  收藏  举报