单链表实例+反转

 

单链表的定义:

struct node
{
int num;
struct node *p;
} ;

在链表节点的定义中,除一个整型的成员外,成员p是指向与节点类型完全相同的指针。

在链表节点的数据结构中,非常特殊的一点就是结构体内的指针域的数据类型使用了未定义成功的数据类型。这是在C中唯一规定可以先使用后定义的数据结构。

 

一个例子:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

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

struct node *init_head()
{
    struct node *new = (struct node *)malloc(sizeof(struct node));

    new->num = 0;
    new->next = NULL;

    return new;
}

struct node * add_node(struct node *head, int num)
{
    struct node *new = (struct node *)malloc(sizeof(struct node));

    new->num = num;
    new->next = head->next; 
    head->next = new;

    return head;
}

struct node *reverse_list(struct node *head)
{
    struct node *p1, *p2, *p3;

    if (head == NULL)
    {
        return NULL;
    }

    p1 = head;
    p2 = head->next;

    while(p2)
    {
        p3 = p2->next;
        p2->next = p1;
        p1=p2;
        p2=p3;
    }

    head->next = NULL;
    head = p1;

    return head;
}

struct node *print_list(struct node *head)
{
    struct node *tmp;
    
    tmp = head;

    while(head != NULL)
    {
        printf("%d, ", head->num);
        head = head->next;
    }

    return tmp;
}

void release_list(struct node *head)
{
    struct node *tmp = NULL;
    
    while(head != NULL)
    {
        tmp = head;
        head = head->next;
        free(tmp);
    }

    return;
}

int main()
{
    struct node *head = NULL;
    int i;

    head = init_head();
    
    for (i=1; i< 10; i++)
    {
        add_node(head, i);
    }

    printf("old list:");
    print_list(head->next);
    printf("\n");


    head->next = reverse_list(head->next);

    printf("new list:");
    head = print_list(head->next);
    printf("\n");

    release_list(head);

    return 0;
}

 

输出为

old list:9, 8, 7, 6, 5, 4, 3, 2, 1, 
new list:1, 2, 3, 4, 5, 6, 7, 8, 9,

 

posted on 2016-06-08 16:01  maxpak  阅读(210)  评论(0编辑  收藏  举报