单链表实现实例

/* list.h */
#ifndef _LINKLIST_H
#define _LINKLIST_H

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

typedef struct node *ptr_to_node;
typedef struct node *position;
typedef struct node *list;

list create_list();
void insert(int x, list l, position p);
void insert_to_head(int x, list l);
void insert_to_tail(int x, list l);
position find_previous(int x, list l);
int is_last(position p, list l);
void delete(int x, list l);
void printl(list l);
void make_empty(list l)

#endif
/* list.c */
#include "list.h"
#include <stdio.h>
#include <errno.h>
#include <stdlib.h>

list 
create_list()
{
    list l;
    l = malloc(sizeof(struct node));
    if(l == NULL)
    {
        perror("malloc error");
        exit(1);
    }
    l->next = NULL;

    return(l);
}

void 
insert(int x, list l, position p)
{
    position newnode;
    newnode = malloc(sizeof(struct node));

    if(newnode == NULL)
    {
        perror("malloc error");
        exit(1);
    }
    newnode->data = x;
    newnode->next = p->next;
    p->next = newnode;
}
void
insert_to_head(int x, list l)
{
    insert(x, l, l);
}
void
insert_to_tail(int x, list l)
{
    ptr_to_node nptr;

    nptr = l;
    while(nptr->next != NULL)
        nptr = nptr->next;
    insert(x, l, nptr);
}
position
find_previous(int x, list l)
{
    position p;
    
    p = l;
    while(p->next != NULL && p->next->data != x)
        p = p->next;

    return(p);
}
int
is_last(position p, list l)
{
    return(p->next == NULL);
}
void
delete(int x, list l)
{
    position p, tmpp;

    p = find_previous(x, l);

    if( !is_last(p, l))
    {
        tmpp = p->next; 
        p->next = tmpp->next;
        free(tmpp);
    }
}
void printl(list l)
{
    position p;
    
    p = l->next;
    while(p != NULL)
    {
        printf("%d->", p->data);
        p = p->next;
    }
    printf("NULL\n");
}

  void make_empty(list l)
  {
      ptr_to_node p, p_next;

      p = l->next;
      while(p != NULL)
     {
         p_next = p->next;
         free(p);
         p = p_next;
     }
     l->next = NULL;
  }

 
/* test.c */
#include "list.h"
#include <stdio.h>

int
main(void)
{    
    list l;
    l = create_list();
    printf("insert from list tail:\n");
    insert_to_tail(1, l);
    insert_to_tail(2, l);
    insert_to_tail(3, l);
    insert_to_tail(4, l);
    insert_to_tail(5, l);
    printl(l);
    printf("after delete 3:\n");
    delete(3, l);
    printl(l);

    putchar('\n');
    printf("insert from list head:\n");
    insert_to_head(1, l);
    insert_to_head(2, l);
    insert_to_head(3, l);
    insert_to_head(4, l);
    insert_to_head(5, l);
    printl(l);
    printf("after delete 3:\n");
    delete(3, l);
    printl(l);
}

 

编译运行:

image

posted @ 2014-03-04 11:21  ITtecman  阅读(753)  评论(0编辑  收藏  举报