单链表反转

单链表反转

  • 单链表初始化
  • 输出
  • 反转
  • 释放

实现代码

#include 
#include 

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

struct node* list_init(int length)
{
        int i = 0;
        struct node *p, *q;
        if(length <= 0) {
                return NULL;
        }else{
                p = malloc(sizeof(struct node));
                p->data = 0;
        }
        for(i=1, q=p; inext = malloc(sizeof(struct node));
                q = q->next;
                q->data = i;
        }
        q->next = NULL;
        return p;
}

int list_print(struct node *pnode)
{
        int i;
        for(i=0; pnode; i++) {
                printf("node[%i]: %i\n", i, pnode->data);
                pnode = pnode->next;
        }
        return 0;
}

struct node* list_reverse(struct node *pnode)
{
        struct node *p, *q = NULL;
        while( pnode ) {
                p = pnode->next;
                pnode->next = q;
                q = pnode;
                pnode = p;
        }
        return q;
}

int list_free(struct node *pnode)
{
        struct node *p, *q;
        p = pnode;

        while(p) {
                q = p->next;
                free(p);
                p = q;
        }
        return 0;
}

int main(int argc, char* argv[])
{
        int len;
        struct node *pnode = NULL;

        printf("input number:");
        scanf("%i", &len);

        pnode = list_init(len);
        list_print(pnode);
        list_print(list_reverse(pnode));
        list_free(pnode);
}

尚未实现

  • 元素插入
  • 元素删除

你可能感兴趣的:(单链表反转)